myssiahjaceyon
myssiahjaceyon

Reputation: 21

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?

Upvotes: 2

Views: 1779

Answers (1)

HTF
HTF

Reputation: 7260

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 ---

Upvotes: 4

Related Questions