python中有内置的跨线程事件吗?

2023-11-25

python 中是否有任何内置语法允许我向问题中的特定 python 线程发布消息?就像 pyQt 中的“排队连接信号”或 Windows 中的 ::PostMessage() 一样。我需要这个来实现程序部分之间的异步通信:有许多线程处理网络事件,它们需要将这些事件发布到单个“逻辑”线程,该线程以安全的单线程方式转换事件。


The Queuemodule is python 非常适合您所描述的内容。

您可以设置一个在所有线程之间共享的队列。处理网络事件的线程可以使用queue.put将事件发布到队列中。逻辑线程将使用queue.get从队列中检索事件。

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中有内置的跨线程事件吗? 的相关文章