I would like to use a queue for passing data from a parent to a child process which is launched via multiprocessing.Process
. However, since the parent process uses Python's new asyncio
library, the queue methods need to be non-blocking. As far as I understand, asyncio.Queue
is made for inter-task communication and cannot be used for inter-process communication. Also, I know that multiprocessing.Queue
has the put_nowait()
and get_nowait()
methods but I actually need coroutines that would still block the current task (but not the whole process). Is there some way to create coroutines that wrap put_nowait()
/get_nowait()
? On another note, are the threads that multiprocessing.Queue
uses internally compatible after all with an event loop running in the same process?
If not, what other options do I have? I know I could implement such a queue myself by making use of asynchronous sockets but I hoped I could avoid that…
EDIT:
I also considered using pipes instead of sockets but it seems asyncio
is not compatible with multiprocessing.Pipe()
. More precisely, Pipe()
returns a tuple of Connection
objects which are not file-like objects. However, asyncio.BaseEventLoop
's methods add_reader()
/add_writer()
methods and connect_read_pipe()
/connect_write_pipe()
all expect file-like objects, so it is impossible to asynchronously read from/write to such a Connection
. In contrast, the usual file-like objects that the subprocess
package uses as pipes pose no problem at all and can easily be used in combination with asyncio
.
UPDATE:
I decided to explore the pipe approach a bit further: I converted the Connection
objects returned by multiprocessing.Pipe()
into file-like objects by retrieving the file descriptor via fileno()
and passing it to os.fdopen()
. Finally, I passed the resulting file-like object to the event loop's connect_read_pipe()
/connect_write_pipe()
. (There is some mailing list discussion on a related issue if someone is interested in the exact code.) However, read()
ing the stream gave me an OSError: [Errno 9] Bad file descriptor
and I didn't manage to fix this. Also considering the missing support for Windows, I will not pursue this any further.