code
from queue import Queue from threading import Thread # 用来表示终止的特殊对象 _sentinel = object() # A thread that produces data def producer(out_q): for i in range(10): print("生产") out_q.put(i) out_q.put(_sentinel) # A thread that consumes data def consumer(in_q): while True: data = in_q.get() if data is _sentinel: in_q.put(_sentinel) break else: print("消费", data) # Create the shared queue and launch both threads q = Queue() t1 = Thread(target=consumer, args=(q,)) t2 = Thread(target=producer, args=(q,)) t1.start() t2.start()
输出
macname@MacdeMBP ~ % python -u "/Users/macname/Desktop/test.py" 生产 生产 消费 0 生产 生产 生产 消费 1 消费 2 消费 3 生产 生产 生产 生产 生产 消费 4 消费 5 消费 6 消费 7 消费 8 消费 9 macname@MacdeMBP ~ %