在导入的多处理处理器子类上使用 .start() 时出现 IOerror

IOerror when using .start() on imported multiprocessing processor subclass

我在使用 python 2.7 多处理(64 位 windows)时遇到问题。假设我有一个文件 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 值,此代码都可以正常执行。但是,如果我然后在另一个文件中导入并 运行 一个 class 实例

from pathfinder import MWE

mwe = MWE(10000)
mwe.start()

我得到以下回溯 if 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() 似乎不会影响此行为。有谁知道为什么会这样,或者如何解决它?

问题在于您如何在 Windows 中使用 multiprocessing。导入定义 Process class 的模块时,例如:

from pathfinder import MWE

您必须将 运行 代码封装在 if __name__ == '__main__': 块中。因此,将您的客户端代码更改为:

from pathfinder import MWE
if __name__ == '__main__':
    mwe = MWE(10000)
    mwe.start()
    mwe.join()

(另外,请注意,您希望在某个时候 join() 您的流程。)

查看 Windows-specific Python 限制文档 https://docs.python.org/2/library/multiprocessing.html#windows

有关类似问题,请参阅 and 。