进程和线程模块下都有队列类。
JoinableQueue示例:
import time,random from multiprocessing import Process,JoinableQueue def producer(name,q): count= 0 while count<3: print(‘making,,,,‘) time.sleep(2) q.put(count) print(‘Producer %s has produced %s baozi‘%(name,count)) count += 1 q.join() # 直到队列清空,程序才会结束 def consumer(name,q): count = 0 while count <3: time.sleep(1) if not q.empty():break data = q.get() print(data) print(‘consumer %s has eat %s baozi‘%(name,count)) count +=1 q.task_done() if __name__ == ‘__main__‘: # 容器 q = JoinableQueue() # 生产者们 p = Process(target=producer,args=(‘A‘,q,)) p.start() # 消费者们 c = Process(target=consumer,args=(‘B‘,q,)) c.daemon = True c.start() p.join()