gpt4 book ai didi

python - 在 Python 中使用 multiprocessing.Array 时出现 OSError (Errno 9)

转载 作者:行者123 更新时间:2023-12-01 00:08:57 26 4
gpt4 key购买 nike

我尝试在 Python 3.7.4 (macOS 10.14.6) 的两个单独进程中使用 multiprocessing.Array。我首先使用 spawn 上下文创建一个新进程,并将 Array 对象作为参数传递给它:

import multiprocessing, time, ctypes


def fn(c):
time.sleep(1)
print("value:", c.value)


def main():
ctx = multiprocessing.get_context("spawn")
arr = multiprocessing.Array(ctypes.c_char, 32)

p = ctx.Process(target=fn, args=(arr,))
p.start()

arr.value = b"hello"
p.join()


if __name__ == "__main__":
main()

但是,当我尝试阅读它时,出现以下错误:

Process SpawnProcess-1:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
self.run()
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "/Users/federico/Workspace/test/test.py", line 6, in fn
print("value:", c.value)
File "<string>", line 3, in getvalue
OSError: [Errno 9] Bad file descriptor

但是,预期输出是value: hello。有人知道这里可能出了什么问题吗?谢谢。

最佳答案

该数组还应该在您为多处理定义的上下文中定义,如下所示:

import multiprocessing, time
import ctypes
from multiprocessing import Process


def fn(arr):
time.sleep(1)
print("value:", arr.value)


def main():
ctx = multiprocessing.get_context("spawn")
arr = ctx.Array(ctypes.c_char, 32)
p = ctx.Process(target=fn, args=(arr,))
p.start()
arr.value = b'hello'
p.join()


if __name__ == "__main__":
main()

关于python - 在 Python 中使用 multiprocessing.Array 时出现 OSError (Errno 9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59772004/

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