1.回调函数 add_done_callback()
但是返回结果是无序的。
1 import time 2 import random 3 from concurrent.futures import ProcessPoolExecutor 4 def func1(n): 5 time.sleep(random.random()) 6 print('in func1 %s'%n) 7 return n*2 8 9 def call_back(arg): 10 print(arg.result()) 11 12 if __name__ == '__main__': 13 p = ProcessPoolExecutor(4) 14 for i in range(10): 15 ret = p.submit(func1,i) 16 ret.add_done_callback(call_back)#是乱序的
运行结果:
2. 运用列表:
1 import time 2 import random 3 from concurrent.futures import ProcessPoolExecutor 4 def func1(n): 5 time.sleep(random.random()) 6 print('in func1 %s'%n) 7 return n*2 8 9 def call_back(arg): 10 print(arg.result()) 11 12 if __name__ == '__main__': 13 p = ProcessPoolExecutor(4) 14 # for i in range(10): 15 # ret = p.submit(func1,i) 16 # ret.add_done_callback(call_back)#是乱序的 17 ret_l = [] 18 for i in range(10): 19 ret = p.submit(func1, i) 20 ret_l.append(ret)#实现了该列表的顺序不是乱序的,在for循环列表中直接放对象 21 # print(ret) 22 for r in ret_l: 23 call_back(r)
运行结果:
3.
1 import time 2 import random 3 from concurrent.futures import ProcessPoolExecutor 4 def func1(n): 5 time.sleep(random.random()) 6 print('in func1 %s'%n) 7 return n*2 8 9 def call_back(arg): 10 print(arg.result()) 11 12 if __name__ == '__main__': 13 p = ProcessPoolExecutor(4) 14 # for i in range(10): 15 # ret = p.submit(func1,i) 16 # ret.add_done_callback(call_back)#是乱序的 17 ret_l = [] 18 for i in range(10): 19 ret = p.submit(func1, i) 20 call_back(ret) 21 # ret_l.append(ret)#实现了该列表的顺序不是乱序的,在for循环列表中直接放对象 22 # print(ret) 23 # for r in ret_l: 24 # call_back(r)
运行结果:
猜想的 不一定对,call_back(ret)接受的是对象 但是call_back函数需要打印ret.result() 使得程序阻塞。