Are there any built-in cross-thread events in pyth

2019-02-16 19:59发布

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.

2条回答
时光不老,我们不散
2楼-- · 2019-02-16 20:32

The Queue module is python is well suited to what you're describing.

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)
查看更多
再贱就再见
3楼-- · 2019-02-16 20:32

I'm not really sure what you are looking for. But there is certainly no built-in syntax for that. Have a look at the queue and threading modules. There is a lot of helpful stuff like Queues, Conditions, Events, Locks and Semaphores that can be used to implement all kind of synchronous and asynchronous communications.

查看更多
登录 后发表回答