bihuchao
2019-01-06 16:23:54 +08:00
multiprocessing 中的 Queue 不能被序列化。
目的应该是这样吧
``` Python
#! /usr/bin/python3
import time
import random
import multiprocessing
queue = multiprocessing.Queue()
def perform_task(id):
print("{0}# process start".format(id))
begin = time.time()
time.sleep(random.random()*5)
print("{0}# process end".format(id))
res = "{0}# process time : {1}".format(id, time.time()-begin)
print(res)
queue.put(res)
return
if __name__ == "__main__":
poolCount = 5
pool = multiprocessing.Pool(poolCount)
for i in range(poolCount):
pool.apply_async(perform_task, args=(i, ))
pool.close()
pool.join()
print("End tasking, print results:")
while True:
res = queue.get()
print(res)
if queue.empty():
break
```
执行结果:
```
0# process start
1# process start
2# process start
3# process start
4# process start
0# process end
0# process time : 0.5990872383117676
1# process end
1# process time : 2.662280559539795
3# process end
3# process time : 3.903242826461792
2# process end
2# process time : 4.440236330032349
4# process end
4# process time : 4.543649435043335
End tasking, print results:
0# process time : 0.5990872383117676
1# process time : 2.662280559539795
3# process time : 3.903242826461792
2# process time : 4.440236330032349
4# process time : 4.543649435043335
```