【发布时间】:2017-04-26 16:10:22
【问题描述】:
我已经玩了一段时间的多处理,有些事情让我感到困惑。 我写了这个简单的代码来说明问题:
from multiprocessing.pool import ThreadPool #I import the packages needed
from time import sleep
def long_task(n): #a simple long task
sleep(1)
print str(n)+" task finished"
pool = ThreadPool(8) #define my threadpool
for x in xrange(10**7): #it could be a while loop too
print x
pool.apply_async(long_task, args=(x,))
在for 循环内,我希望我的代码等到8 个线程之一完成后再开始另一个线程,但是x 正在打印而没有任何中断。
为什么会这样?我如何得到我正在寻找的东西?这段代码优化了吗?
样本输出:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
【问题讨论】:
-
请提供示例输出。
print x应该立即运行 10**7 次。print str(n)+" task finished"将在每批 8 个之间延迟一秒运行。 -
是的。同样在计数到 10**7-1 时,我的答案中应该有一些表格的打印输出。
标签: python multithreading python-2.7 optimization threadpool