Are there any built-in cross-thread events in python?(python中是否有任何内置的跨线程事件?)
问题描述
python 中是否有任何内置语法允许我向问题中的特定 python 线程发布消息?就像 pyQt 中的排队连接信号"或 Windows 中的 ::PostMessage().我需要它用于程序部分之间的异步通信:有许多处理网络事件的线程,它们需要将这些事件发布到单个逻辑"线程,该线程以安全的单线程方式转换事件.
Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they need to post these events to a single 'logic' thread that translates events safe single-threaded way.
推荐答案
队列 module is python 非常适合您所描述的内容.
The Queue module is python is well suited to what you're describing.
您可以设置一个在所有线程之间共享的队列.处理网络事件的线程可以使用 queue.put 将事件发布到队列中.逻辑线程将使用 queue.get 从队列中检索事件.
You could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. The logic thread would use queue.get to retrieve events from the queue.
import Queue
# maxsize of 0 means that we can put an unlimited number of events
# on the queue
q = Queue.Queue(maxsize=0)
def network_thread():
while True:
e = get_network_event()
q.put(e)
def logic_thread():
while True:
# This will wait until there are events to process
e = q.get()
process_event(e)
这篇关于python中是否有任何内置的跨线程事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python中是否有任何内置的跨线程事件?
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01