从另一个函数调用函数并继续(不要等待完成)python

Kyl*_*Ace 2 python background function multiprocessing

我读了很多关于多处理、线程的文章,但我仍然对简单的事情有疑问。我有2个功能。我想一个接一个地调用并移动一个(这个被调用的函数不能减慢我的速度)。

例子

def main():
    print("my operations")
    Thread(target=child(), args=()).start()
    print("rest operations")


def child():
    #here are some operations that takes 3 seconds
    print("background operations")
Run Code Online (Sandbox Code Playgroud)

关键是子函数的操作不能减慢我的速度。我想调用该函数并继续。所以我想要这样的输出:

my operations
rest operations
background operations
Run Code Online (Sandbox Code Playgroud)

但这样做Thread(target=child(), args=()).start()看起来像

my operations
Run Code Online (Sandbox Code Playgroud)
#then call child function wait 3 seconds
Run Code Online (Sandbox Code Playgroud)
background operations
rest operations
Run Code Online (Sandbox Code Playgroud)

有没有办法做我想做的事?

Tur*_*son 8

当你这样做时

Thread(target=child(), args=()).start()
Run Code Online (Sandbox Code Playgroud)

您在主线程上调用子进程,然后将结果作为目标传递!您想要传递child函数本身,而不是调用它的结果:

Thread(target=child, args=()).start()
Run Code Online (Sandbox Code Playgroud)