简体   繁体   中英

OSError (Errno 9) when using multiprocessing.Array in Python

I'm trying to use a multiprocessing.Array in two separate processes in Python 3.7.4 (macOS 10.14.6). I start off by creating a new process using the spawn context, passing as an argument to it an Array object:

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()

However, when I try to read it, I get the following error:

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

The expected output, however, is value: hello . Anyone know what could be going wrong here? Thanks.

The array should also be defined in the context that you define for the multiprocessing like so:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM