python中是否有内置的跨线程事件? [英] Are there any built-in cross-thread events in python?

查看:131
本文介绍了python中是否有内置的跨线程事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中是否有任何内置的语法,允许我在我的问题中发布一条消息到特定的python线程?像Windows中的pyQt或:: 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.

推荐答案

队列<一个>模块是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中是否有内置的跨线程事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆