异步

主进程在执行的时候不知道系统什么时候让你去执行另外一件事情

好处就是与同步相比,不用等待任务产生。

from multiprocessing import Pool
import time
import os


def test():
print("----------进程中的进程----pid=%d, ppid=%d"%(os.getpid(), os.getppid()))
for i in range(3):
print("---%d"%i)
time.sleep(1)
return "haha"


def test2(args):
print("---call back func---pid=%d"%os.getpid())
print("---call back func---arg=%s"%args)


if __name__ == "__main__":
pool = Pool(3)
pool.apply_async(func=test, callback=test2)
time.sleep(5)
print("----------主进程---pid=%d"%os.getpid())

result:

----------进程中的进程----pid=21732, ppid=20028
---0
---1
---2
---call back func---pid=20028
---call back func---arg=haha
----------主进程---pid=20028

Process finished with exit code 0

从结果看在子线程test结束之后,正常来说主线程应该还是在sleep中,但是这时候系统会让主线程起来去执行test2函数,从pid就可以看出来是主线程在调用test2, 而且test2参数还是test返回值,执行完test2之后,主线程会继续执行自己的任务

原文地址:https://www.cnblogs.com/shamoguzhou/p/15215973.html