python 生产消费模型出现无限挂起的可能原因

from queue import Queue
import logging
import threading
import time

Q = Queue()
threads = []


def consumer(Q: Queue, threads: list):
   logging.debug('准备消费...')
   while threads or not Q.empty():
       for t in threads:
           if not t.is_alive():
               threads.remove(t)
       try:
           d = Q.get()
       except:
           pass
       else:
           logging.debug('{},{}'.format(d, threading.current_thread().name))



def producer(Q: Queue):
   for i in range(100):
       time.sleep(0.1) #模拟 io 耗时操作
       Q.put(i)


logging.basicConfig(
   level=logging.DEBUG,
   format='%(asctime)s (%(threadName)-2s) %(message)s'
)

condition = threading.Condition()

p = threading.Thread(
   name='p',
   target=producer,
   args=(Q,)
)

threads.append(p)
p.start()
for _ in range(2):
   t = threading.Thread(target=consumer, args=(Q,threads))
   t.start()

这种情况会出现队列拿空但是主线程不会结束的情况,这是因为最后一次进入while循环时(此时的条件是队列拿空,threads里还有线程没移除),Q被拿空,Q.get()阻塞,threads.remove(t)一直无法执行。
解决办法是Q.get(timeout=1)

你可能感兴趣的:(python 生产消费模型出现无限挂起的可能原因)