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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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)
回答2:
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.