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中是否有任何内置的跨线程事件?
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01