什么';使用Python实现单个消费者、多个生产者场景的最佳方法是什么?
我有一个Python程序,它生成多个生产者线程,然后有一个循环,等待什么';使用Python实现单个消费者、多个生产者场景的最佳方法是什么?,python,multithreading,synchronization,producer-consumer,Python,Multithreading,Synchronization,Producer Consumer,我有一个Python程序,它生成多个生产者线程,然后有一个循环,等待队列对象包含某些内容。看起来像这样 for t in threads: t.start() while len(threads): if not queue.empty(): response = queue.get() # handle response queue.task_done() else: sleep(1) thread
队列
对象包含某些内容。看起来像这样
for t in threads:
t.start()
while len(threads):
if not queue.empty():
response = queue.get()
# handle response
queue.task_done()
else:
sleep(1)
threads = [t for t in threads if t.is_alive()]
必须有一种更优雅的方式来做到这一点。我已经研究了线程化
模块提供的所有同步对象,但我不知道如何应用它们
仅供参考,我的代码适用于我正在尝试的工作。我坚信不要修复未损坏的东西,但我只是觉得有一种更好的方法可以做到这一点,这是一个更好的程序员在一开始就应该做到的。如果线程仍然处于活动状态,您可以使用
weakref
来测试:
import weakref
def consumer(queue, threads):
while threads:
try:
response = queue.get(timeout=1)
# handle response
queue.task_done()
except Empty:
pass
threads = weakref.WeakSet()
for i in range(10):
t = threading.Thread(...)
t.start()
threads.add(t)
del t # remove all references to threads
consumer(queue, threads)
@丹尼尔:weakref是个很酷的把戏。这里有一个替代方法,它只使用添加了“终止策略”的队列 您将需要确保每个生产者的线程目标函数始终将最终的“终止消息”放入队列,基本上在它们完成生产后为“无”。使用者只需等待,直到接收到适当数量的终止(每个生产者线程1个)并退出循环。这样,您就不必检查线程是否已结束,并且实际上只有一个通信点:队列。但是,如果使用者中存在异常,则生产者线程可能应处于“守护进程”模式,以便它们在等待使用者队列运行时不会阻塞进程。。嗯,是的 您必须确保始终为每个生产者发送终止消息,采用某种try finally缩进。否则,您必须在使用者的“除空”中处理超时
import functools
def consumer(queue,num_threads_remaining):
next_message=functools.partial(iter,functools.partial(queue.get,timeout=1),None)
while num_threads_remaining:
try:
for response in next_message():
# handle response.. hopefully exception-protected
queue.task_done()
# we got a None termination message
num_threads_remaining -= 1
except Empty: pass # handle some other check when idling?