'How would I run a while loop on a separate thread in Python?

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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1