简体   繁体   English

Python 的 asyncio `loop.create_task(...)` 是线程安全的吗?

[英]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.

相关问题 Python asyncio loop.create_task 和 asyncio.run_coroutine_threadsafe 的区别 - Python asyncio difference between loop.create_task and asyncio.run_coroutine_threadsafe 使用 loop.create_task 创建的 asyncio 的 EventLoop 任务是 FIFO - Are asyncio's EventLoop tasks created with loop.create_task a FIFO 从 loop.create_task() 引发的 python asyncio 异常 - python asyncio exceptions raised from loop.create_task() loop.create_task、asyncio.async/ensure_future 和 Task 有什么区别? - What's the difference between loop.create_task, asyncio.async/ensure_future and Task? asyncio:loop.run_until_complete(loop.create_task(f))打印出“永远不会检索到任务异常”,即使它已经被传播了 - asyncio: loop.run_until_complete(loop.create_task(f)) prints “Task exception was never retrieved” even though it clearly was propagated 为什么 loop.create_task 需要这么长时间才能执行? - Why is loop.create_task taking so long to execute? Python asyncio - 如何创建任务列表并在事件循环中使用它? - Python asyncio - How to create task list and use it in the event loop? asyncio create task and aiohttp, 'no running event loop' - asyncio create task and aiohttp , 'no running event loop' python Threadsafe循环锁定 - python Threadsafe lock on loop Python asyncio:可中断的任务 - Python asyncio: interruptable task
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM