I'm developing an application that mainly consists of services which are threads with custom run loops.
One of the services needs to spawn subprocesses and I don't really understand whether it's valid or not. Official documentation is ambiguous. Namely it says both asyncio supports running subprocesses from different threads
and An event loop must run in the main thread
in the same section.
How is it even possible to run subprocess from different threads if event loop must run in the main thread?
subprocess. Process class is not thread safe. The Concurrency and multithreading in asyncio section.
Create a subprocess: low-level API using subprocess. Popen. Run subprocesses asynchronously using the subprocess module.
asyncio. run(main()) asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
asyncio. get_event_loop() Get the current event loop. If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.
Documentation says:
asyncio.get_child_watcher()
at the start of the program.After that you may create subprocess from non-main thread.
UPD
Starting from Python 3.8 asyncio has no limitations mentioned above.
Everything just works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With