python中是否有任何内置的跨线程事件?

Are there any built-in cross-thread events in python?(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中是否有任何内置的跨线程事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)