【发布时间】:2018-08-05 23:37:56
【问题描述】:
这里的新手:我正在尝试串行执行一些代码,然后创建一个线程池并并行执行一些代码。并行执行完成后,我想串行执行更多代码。
例如...
import time
from multiprocessing import Pool
print("I only want to print this statement once")
def worker(i):
"""worker function"""
now = time.time()
time.sleep(i)
then = time.time()
print(now, then)
if __name__ == '__main__':
with Pool(3) as p:
p.map(worker, [1, 1, 1])
p.close()
print("Only print this once as well")
我希望这个返回...
I only want to print this statement once
1533511478.0619314 1533511479.0620182
1533511478.0789354 1533511479.0791905
1533511478.0979397 1533511479.098235
Only print this once as well
然而它返回的是这样的:
I only want to print this statement once
I only want to print this statement once
Only print this once as well
I only want to print this statement once
Only print this once as well
I only want to print this statement once
Only print this once as well
I only want to print this statement once
Only print this once as well
I only want to print this statement once
Only print this once as well
1533511478.0619314 1533511479.0620182
1533511478.0789354 1533511479.0791905
1533511478.0979397 1533511479.098235
Only print this once as well
所以它似乎为每个池额外运行了一次打印语句。
任何帮助将不胜感激!
【问题讨论】:
标签: python multiprocessing python-multiprocessing pool