我遇到了python 2.7多处理(64位窗口)的问题。假设我有一个文件pathfinder.py
,代码为:
import multiprocessing as mp
class MWE(mp.Process):
def __init__(self, n):
mp.Process.__init__(self)
self.daemon = True
self.list = []
for i in range(n):
self.list.append(i)
def run(self):
print "I'm running!"
if __name__=='__main__':
n = 10000000
mwe = MWE(n)
mwe.start()
此代码对于任意大的n值执行正常。但是,如果我然后在另一个文件中导入并运行一个类实例
from pathfinder import MWE
mwe = MWE(10000)
mwe.start()
我得到以下追溯 如果 n> = ~10000 :
Traceback (most recent call last):
File <filepath>, in <module>
mwe.start()
File "C:\Python27\lib\multiprocessing\process.py", line 130, in start
self._popen = Popen(self)
File "C:\Python27\lib\multiprocessing\forking.py", line 280, in __init__
to_child.close()
IOError: [Errno 22] Invalid argument
我认为这可能是某种竞争条件错误,但使用time.sleep来延迟mwe.start()似乎不会影响此行为。有谁知道为什么会这样,或者如何绕过它?
答案 0 :(得分:1)
问题在于如何在Windows中使用multiprocessing
。导入定义Process
类的模块时,例如:
from pathfinder import MWE
您必须将正在运行的代码封装在if __name__ == '__main__':
块中。因此,请将您的客户端代码更改为:
from pathfinder import MWE
if __name__ == '__main__':
mwe = MWE(10000)
mwe.start()
mwe.join()
(另请注意,您希望在某个时候join()
您的流程。)
查看特定于Windows的Python限制文档https://docs.python.org/2/library/multiprocessing.html#windows。
有关类似问题,请参阅https://stackoverflow.com/a/16642099/1510289和https://stackoverflow.com/a/20222706/1510289。