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)
相关文章