Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run parallel jobs in python3 with asyncio?

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?

like image 524
roboslone Avatar asked Jul 29 '14 09:07

roboslone


1 Answers

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()))
like image 148
leech Avatar answered Oct 12 '22 23:10

leech