这是我的代码:
import multiprocessing
import time
import os
def worker():
print str(os.getpid()) + " is going to sleep..."
time.sleep(1)
print str(os.getpid()) + " woke up!"
return
if __name__ == "__main__":
pool = multiprocessing.Pool(processes = 8)
for _ in range(5):
pool.apply_async(worker())
我的输出:
23173 is going to sleep...
23173 woke up!
23173 is going to sleep...
23173 woke up!
23173 is going to sleep...
23173 woke up!
23173 is going to sleep...
23173 woke up!
23173 is going to sleep...
23173 woke up!
此输出按顺序显示,显然所有输出都具有相同的ID。我期待看到的是5个独立的过程,警告他们将要睡觉,然后在相似的时间醒来。
为什么不发生这种情况?我已经对stackoverflow和其他网站做了很多研究,似乎每个人都确信这应该有" worker"可调用应用于多个进程,但似乎不是。
答案 0 :(得分:2)
您正在调用 worker
函数,因此当前进程执行该代码,然后结果{{1 (即worker
)传递给None
,它什么都不做。
将函数 apply_asynch
传递给执行它的子进程,将其更改为pool.apply_asynch(worker)
。
要清楚,问题在于:
worker
而且:
>>> def worker():
... print('Hi there!')
...
>>> def f(func):
... print('Received', func)
... func()
...
>>> f(worker())
Hi there!
Received None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
TypeError: 'NoneType' object is not callable
请注意,前者的行顺序错误,并生成>>> f(worker)
Received <function worker at 0x7f5cd546f048>
Hi there!
。
不幸的是,TypeError
默认情况下会使异常静音。您可以处理传递额外参数的错误。