from multiprocessing import JoinableQueue from threading import Thread def worker(q): while True: try: item = q.get() print(item) if item % 5 == 0: if item == 5: time.sleep(20) q.put(111) q.task_done() except Exception as e: print(e) q = JoinableQueue() import time def customer(q): for i in range(100): try: q.put(i) except Exception as e: print(e) ct = Thread(target=customer, name='customer', args=(q,)) ct.daemon = True ct.start() ct.join() for i in range(4): t = Thread(target=worker, name='worker'+str(i), args=(q,)) t.daemon = True t.start() q.join() print('end')
一旦消费者速度快,生产者速度慢,可能导致提前结束
所以添加任务不能起一个线程,一直加,一旦速度慢下来,就提前结束了。
保险的是在worker中 task_done之前添加。