0x00:前言
线程之间有时需要通信,操作系统提供了很多机制来实现进程间的通信,其中我们使用最多的是队列Queue.
0x01:Queue的原理
Queue是一个先进先出(First In First Out)的队列,主进程中创建一个Queue对象,并作为参数传入子进程,两者之间通过put( )放入数据,通过get( )取出数据,执行了get( )函数之后队列中的数据会被同时删除,可以使用multiprocessing模块的Queue实现多进程之间的数据传递。
import threading, queueimport timedef produce():for i in range(10):time.sleep(0.5)print('生产++++++面包{} {}'.format(threading.current_thread().name, i))q.put('{}{}'.format(threading.current_thread().name, i))def consumer():while True:time.sleep(1)# q.get()方法时一个阻塞的方法print('{}买到------面包{}'.format(threading.current_thread().name, q.get()))q = queue.Queue() # 创建一个q# 一条生产线pa = threading.Thread(target=produce, name='pa')pb = threading.Thread(target=produce, name='pb')pc = threading.Thread(target=produce, name='pc')# 一条消费线ca = threading.Thread(target=consumer, name='ca')cb = threading.Thread(target=consumer, name='cb')cc = threading.Thread(target=consumer, name='cc')pa.start()pb.start()pc.start()ca.start()cb.start()cc.start()
