1

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.

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Genius. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.