码迷,mamicode.com
首页 > 编程语言 > 详细

Python 生产者消费者模型

时间:2018-12-01 23:28:23      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:start   port   div   测试   oca   coding   use   生产者消费者模型   star   

一、简单的生产者消费者模型

 1 #!/usr/bin/python
 2 # -*- coding : utf-8 -*-
 3 # 作者: Presley
 4 # 时间: 2018-12-1
 5 # 邮箱:1209989516@qq.com
 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:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.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 生产者消费者模型

标签:start   port   div   测试   oca   coding   use   生产者消费者模型   star   

原文地址:https://www.cnblogs.com/Presley-lpc/p/10051234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!