How do I run parallel jobs in python3 with asyncio?
-
20-12-2019 - |
Question
Assuming, that I have a class like that:
class MyClass:
def __init__(self):
run_some_long_time_function()
How can I create many instances of this class in parallel using asyncio in python 3.4.1?
Solution
The asyncio event loop is single threaded, so nothing running on the event loop will run in parallel. You can however spawn a thread and wait for it to finish. The default executor should create a thread for you:
loop = asyncio.get_event_loop()
asyncio.async(loop.run_in_executor(None, lambda: MyClass()))
asyncio.async(loop.run_in_executor(None, lambda: MyClass()))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow