Starts an infinite loop in the asyncio event loop, which starts the main thread

I wrote code that seems to do what I want, but I'm not sure if this is a good idea, as it mixes threads and event loops to start an infinite loop from the main thread. This is a minimal piece of code that reflects the idea of ​​what I am doing:

import asyncio
import threading

msg = ""

async def infinite_loop():
    global msg
    while True:
        msg += "x"
        await asyncio.sleep(0.3)

def worker():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.get_event_loop().run_until_complete(infinite_loop())

t = threading.Thread(target=worker, daemon=True)
t.start()

The basic idea is that I have an infinite loop controlling a global variable every 0.3 s. I want this infinite loop to work with the main thread, so I can access the shared variable in the main thread. This is especially useful in jupyter, because if I call run_until_completein the main thread, I can no longer interact with jupyter. I want the main thread to be available for interactive access and changemsg. async , , . async threading python, , /, threading asyncio ... ? concurrency ?

+3
1

async threading python, , /, threading asyncio ...

asyncio threading , , . , asyncio, , , .

, asyncio, - , , asyncio . , ( , call_soon, create_task, stop ..) , , . , , , loop.call_soon_threadsafe() asyncio.run_coroutine_threadsafe().

, .. "", asyncio . , , , .

?

, , :

: , jupyter, asyncio, , .

concurrency ?

GIL , , .

, ​​ , , . , , , threading.Event asyncio coroutine, . asyncio.Event , - loop.call_soon_threadsafe(event.set) .

0

Source: https://habr.com/ru/post/1695595/


All Articles