Python 需要线程安全的异步消息队列
我正在寻找一个Python类(最好是标准语言的一部分,而不是第三方库)来管理异步“广播式”消息传递 我将有一个线程将消息放在队列上(“putMessageOnQueue”方法不能阻塞),然后有多个其他线程都将等待消息,可能调用了一些阻塞的“WaitFormMessage”函数。当消息被放置在队列上时,我希望每个等待的线程都获得自己的消息副本 我已经研究了内置的Python 需要线程安全的异步消息队列,python,multithreading,queue,message-queue,Python,Multithreading,Queue,Message Queue,我正在寻找一个Python类(最好是标准语言的一部分,而不是第三方库)来管理异步“广播式”消息传递 我将有一个线程将消息放在队列上(“putMessageOnQueue”方法不能阻塞),然后有多个其他线程都将等待消息,可能调用了一些阻塞的“WaitFormMessage”函数。当消息被放置在队列上时,我希望每个等待的线程都获得自己的消息副本 我已经研究了内置的Queue类,但我认为这不合适,因为消费消息似乎需要将它们从队列中删除,因此每个消息只有一个客户端线程可以看到 这似乎应该是一个常见的用例
Queue
类,但我认为这不合适,因为消费消息似乎需要将它们从队列中删除,因此每个消息只有一个客户端线程可以看到
这似乎应该是一个常见的用例,有人能推荐一个解决方案吗?我认为典型的方法是为每个线程使用一个单独的消息队列,并将消息推送到以前对接收此类消息感兴趣的每个队列上 像这样的东西应该可以工作,但它是未经测试的代码
from time import sleep
from threading import Thread
from Queue import Queue
class DispatcherThread(Thread):
def __init__(self, *args, **kwargs):
super(DispatcherThread, self).__init__(*args, **kwargs)
self.interested_threads = []
def run(self):
while 1:
if some_condition:
self.dispatch_message(some_message)
else:
sleep(0.1)
def register_interest(self, thread):
self.interested_threads.append(thread)
def dispatch_message(self, message):
for thread in self.interested_threads:
thread.put_message(message)
class WorkerThread(Thread):
def __init__(self, *args, **kwargs):
super(WorkerThread, self).__init__(*args, **kwargs)
self.queue = Queue()
def run(self):
# Tell the dispatcher thread we want messages
dispatcher_thread.register_interest(self)
while 1:
# Wait for next message
message = self.queue.get()
# Process message
# ...
def put_message(self, message):
self.queue.put(message)
dispatcher_thread = DispatcherThread()
dispatcher_thread.start()
worker_threads = []
for i in range(10):
worker_thread = WorkerThread()
worker_thread.start()
worker_threads.append(worker_thread)
dispatcher_thread.join()
我认为这是一个更直截了当的示例(取自中的队列示例)
我相信你可以建立自己的类,跟踪哪个线程得到了哪个消息,没有很多问题。太好了,太好了!遗憾的是,没有现成的版本,但我想,一旦有人清楚地解释了它(就像你所做的那样),原理就不会那么复杂了。@codebox好吧,模块中有更好的支持,但这是针对子进程而不是线程的。我猜这是因为进程间通信通常比线程间通信更复杂,因为线程自然共享同一堆。如果需要一个编写器的广播,队列是最佳解决方案吗?也许最好使用一次写入/多次读取结构,每个进程都可以在自己的空闲时间并发读取?这如何满足问题的要求?他明确表示,队列不起作用,因为每个线程都需要该项的副本。
from threading import Thread
from Queue import Queue
num_worker_threads = 2
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done