Python 生产者消费者模型
Posted Presley
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 生产者消费者模型相关的知识,希望对你有一定的参考价值。
一、简单的生产者消费者模型
1 #!/usr/bin/python 2 # -*- coding : utf-8 -*- 3 # 作者: Presley 4 # 时间: 2018-12-1 5 # 邮箱:[email protected] 6 # 这是我用来练习python 生产者消费者模型的测试脚本 7 8 import threading,queue 9 10 def consume(n): 11 print("consumer [%s] get task: %s" %(n,q.get())) 12 q.task_done() 13 14 def producer(n): 15 for i in range(2): 16 print("producer [%s] produced a new task: %s" %(n,i)) 17 q.put(i) 18 #q.join() 19 print("all taks has been cosumed by consumers...") 20 21 q = queue.Queue() 22 23 c1 = threading.Thread(target=consume,args=[1,]) 24 c2 = threading.Thread(target=consume,args=[2,]) 25 c3 = threading.Thread(target=consume,args=[3,]) #因为只做了两个包子因此第三个消费者会一直阻塞住 26 27 p = threading.Thread(target=producer,args=["wohaoshuai",]) 28 29 c1.start() 30 c2.start() 31 c3.start() 32 33 p.start()
执行结果:
1 C:UserswohaoshuaiAppDataLocalProgramsPythonPython36python.exe E:/PythonLearn/day16/pro_consume.py 2 producer [wohaoshuai] produced a new task: 0 3 producer [wohaoshuai] produced a new task: 1 4 all taks has been cosumed by consumers... 5 consumer [2] get task: 0 6 consumer [1] get task: 1
以上是关于Python 生产者消费者模型的主要内容,如果未能解决你的问题,请参考以下文章