[英]Is Python's asyncio `loop.create_task(...)` threadsafe?
I have matplotlib running on the main thread with a live plot of data coming in from an external source.我有 matplotlib 在主线程上运行,有来自外部源的实时数据 plot。 To handle the incoming data I have a simple UDP listener listening for packages using asyncio with the event loop running on a seperate thread.
为了处理传入的数据,我有一个简单的 UDP 侦听器使用 asyncio 侦听包,事件循环在单独的线程上运行。
I now want to add more sources and I'd like to run their listeners on the same loop/thread as the first one.我现在想添加更多来源,并且我想在与第一个相同的循环/线程上运行他们的侦听器。 To do this I'm just passing the loop object to the classes implementing the listeners and their constructor adds a task to the loop that will initialize and run the listener.
为此,我只是将循环 object 传递给实现侦听器的类,并且它们的构造函数向将初始化并运行侦听器的循环添加了一个任务。
However since these classes are initialized in the main thread I'm calling the loop.create_task(...)
function from there instead of the loop's thread.但是,由于这些类是在主线程中初始化的,所以我从那里调用
loop.create_task(...)
function 而不是循环的线程。 Will this cause any issues?这会导致任何问题吗?
The answer is no, using loop.create_task(...)
to schedule a coroutine from a different thread is not threadsafe, use asyncio.run_coroutine_threadsafe(...) instead.答案是否定的,使用
loop.create_task(...)
从不同线程调度协程不是线程安全的,请改用asyncio.run_coroutine_threadsafe(...) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.