gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:14 24 4
gpt4 key购买 nike

我在使用 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 值,此代码都可以正常执行。但是,如果我随后在另一个文件中导入并运行类实例

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 中使用多处理。导入定义 Process 类的模块时,例如:

from pathfinder import MWE

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

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/1510289https://stackoverflow.com/a/20222706/1510289对于类似的问题。

关于python - 在导入的多处理处理器子类上使用 .start() 时出现 IOerror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34568146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com