作业-线程-生产-消费模型
1 from threading import Thread, currentThread 2 import queue, time, random 3 4 5 def customer(): 6 while True: 7 time.sleep(random.randint(1,3)) 8 res = q.get() 9 print('\033[45m%s 吃了%s\033[0m' % (currentThread().getName(), res)) 10 q.task_done() 11 12 13 def producer1(): 14 for i in range(10): 15 time.sleep(1) 16 print('\033[44m%s 生产了包子%s\033[0m' % (currentThread().getName(), i+1)) 17 q.put('包子%s' % (i+1)) 18 q.join() 19 20 21 def producer2(): 22 for i in range(10): 23 time.sleep(1) 24 print('\033[42m%s 生产了饺子%s\033[0m' % (currentThread().getName(), i+1)) 25 q.put('饺子%s' % (i+1)) 26 q.join() 27 28 if __name__ == '__main__': 29 q = queue.Queue() 30 p1 = Thread(target=producer1) 31 p1.start() 32 33 p2 = Thread(target=producer2) 34 p2.start() 35 36 for j in range(2): 37 c = Thread(target=customer) 38 c.daemon = True 39 c.start() 40 41 p1.join() 42 p2.join()
简单解释一下吧
两个生产者producer1,producer2
两个消费者customer 做成守护进程
通过Queue实现线程间数据传递(优点:自带锁,省去加锁释放锁)
通过q.task_done()传递q中的数据减少情况
通过q.join()监控q中是否还有数据
当q中无数据时,线程结束,
主线程结束前,关闭守护进程,线程结束