还是卖包子的故事, 我们在生产者消费者模型里面,消费者一直问有没有包子,生产者一直生产包子
那么可不可以这样,消费者过来问:有没有包子的时候,告诉他没有,等过会做好了,叫你。
我们可以通过event来做线程间信号传递
1 __author__ = ‘Rico‘ 2 #coding:utf-8 3 4 import threading 5 import time 6 7 8 def Producer(): 9 print ‘cook:wait for somebody‘ 10 event.wait() 11 event.clear() 12 print ‘cook:somebody is coming for baozi‘ 13 print ‘make some baozi‘ 14 time.sleep(5) 15 print ‘The baozi is ready‘ 16 event.set() 17 def Consumer(): 18 print u‘jack:go buy some baozi‘ 19 event.set() 20 time.sleep(2) 21 while 1: 22 if event.is_set(): 23 print ‘Thinks‘ 24 break 25 else: 26 print ‘Please do it quickly ‘ 27 time.sleep(1) 28 29 event = threading.Event() 30 p = threading.Thread(target=Producer) 31 c = threading.Thread(target=Consumer) 32 p.start() 33 c.start()
时间: 2024-10-11 07:46:49