Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asyncio asynchronously run a function

In python, I am trying to run an asynchronous function asynchronously in a thread. My code right now is

import time
import asyncio

async def test():
    print('Started!')
    time.sleep(2)
    print('Ok!')

async def main():
    loop = asyncio.get_event_loop()
    start_time = time.time()
    await asyncio.gather(*(loop.run_in_executor(None, test) for i in range(5)))
    print("--- %s seconds ---" % (time.time() - start_time))

asyncio.run(main())

But this gives me the error RuntimeWarning: Enable tracemalloc to get the object allocation traceback.

I have also tried

await asyncio.gather(*(asyncio.to_thread(test) for i in range(5)))

But that does not work with blockingcode (like the time.sleep I have). It starts only one thread and does the time.sleep one by one. How do I solve this?

like image 636
myssiahjaceyon Avatar asked May 12 '26 10:05

myssiahjaceyon


1 Answers

Don't mix sync with async code. Your test function is blocking and adding just the async keyword won't make it asynchronous:

import time
import asyncio


def test():
    print("Started!")
    time.sleep(2)
    print("Ok!")


async def main():
    start_time = time.time()

    await asyncio.gather(*(asyncio.to_thread(test) for i in range(5)))

    print("--- %s seconds ---" % (time.time() - start_time))


if __name__ == "__main__":
    asyncio.run(main())

Test:

$ python test.py
Started!
Started!
Started!
Started!
Started!
Ok!
Ok!
Ok!
Ok!
Ok!
--- 2.0036470890045166 seconds ---
like image 137
HTF Avatar answered May 13 '26 22:05

HTF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!