Python 回调函数

2019-10-13  本文已影响0人  陈忠俊

所有的进程调用test2函数,test2 输出test1对应进程里的数据

from multiprocessing import Pool
import time
import os
def test1(n):
    print(os.getppid())
    print(time.asctime(), os.getpid())
    print("test1.func is running")
    time.sleep(0.5)
    return n + 1

def test2(m):
    print(time.time(), os.getpid())
    print("test2.func is running")
    print(m)

if __name__ == "__main__":
    p = Pool(2)
    for i in range(10, 14):
        p.apply_async(test1, args = (i,), callback = test2)
    p.close()
    p.join()

输出结果

$ py -3 callback_func.py
15076
Sun Oct 13 17:42:46 2019 14684
test1.func is running
15076
Sun Oct 13 17:42:46 2019 12792
test1.func is running
1570959767.107586 15076
test2.func is running
11
1570959767.1114893 15076
test2.func is running
12
15076
Sun Oct 13 17:42:47 2019 14684
test1.func is running
15076
Sun Oct 13 17:42:47 2019 12792
test1.func is running
1570959767.624987 15076
test2.func is running
13
1570959767.6268208 15076
test2.func is running
14
上一篇 下一篇

猜你喜欢

热点阅读