import time,random
import queue,threading
q = queue.Queue()
# q.put(2)
# q.join()
# q.put(3)
def Producer(name):
count = 0
while count <10:
print("making........")
time.sleep(5)
q.put(count)
print('Producer %s has produced %s baozi..' %(name, count))
count +=1
q.task_done()#在队列里放数据之后,告诉一下队列,我往里面放了一个数据
#q.join()
print("ok......")
def Consumer(name):
count = 0
while count <10:
time.sleep(random.randrange(4))
# if not q.empty():
# print("waiting.....")
#q.join()#我在这边收到你放了一条数据之后的消息后 q.task_done(),我这边才会往下执行,否则阻塞
data = q.get()
print("eating....")
time.sleep(4)
#q.task_done()
#print(data)
print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data))
# else:
# print("-----no baozi anymore----")
count +=1
p1 = threading.Thread(target=Producer, args=('A君',))
c1 = threading.Thread(target=Consumer, args=('B君',))
c2 = threading.Thread(target=Consumer, args=('C君',))
c3 = threading.Thread(target=Consumer, args=('D君',))
p1.start()
c1.start()
c2.start()
c3.start()
Python(生产消费者模型)
最新推荐文章于 2024-08-08 08:27:49 发布