0

I'm new to coroutines in python but I know in lua you would do this to create one

coroutine.wrap(function()
 while true do
 end
end)()

But I dont know how I would do this python.

I tried using this code which included a function from the slp_coroutine library which didnt work

import slp_coroutine
def test():
    while True:
        print("hi")
        time.sleep(3)

r = slp_coroutine.await_coroutine(test())

and I also tried this and it also didnt work.

async def test():
    while True:
        print("hi")
        await asyncio.sleep(3)

asyncio.run(test())
  • If you just want threads, that is what `threading` is there for. In the Python ecosystem, an explicit "coroutine" is usually used for *very* high concurrency - some hundred to several thousands of tasks. – MisterMiyagi Apr 02 '22 at 05:49
  • This [link](https://stackoverflow.com/q/2846653/4897206) might help you. – Ashutosh Kumar Apr 02 '22 at 06:12

1 Answers1

0

You need an event loop for concurrency or else your just syncronously running a function marked as async.

import asyncio

async def test1():
    while True:
        print("hi 1")
        await asyncio.sleep(1)

async def test2():
    while True:
        print("hi 2")
        await asyncio.sleep(2)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    task = loop.create_task(test1())
    task = loop.create_task(test2())
    loop.run_forever()

Keep in mind python async is not multi-threaded, you get 1 event loop per thread, and if you wind up calling a long running function inside the event loop, the entire loop and all tasks will be waiting for that long running function.

In case you need a long running function, you would export that into a thread and await for the result so the loop can work on other things. An example of such behavior can be seen here.

0xKate
  • 197
  • 8