python用于实现多线程异步交互之生产者消费者模型
1
2
3
4
|
1 .生产者消费者模型:厨师做包子与顾客吃包子
2 .Python的消息队列
3 .利用消息队列实现Python多线程异步交互
4 .再谈耦合度的问题
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/usr/bin/env python
import threading, time
import Queue #导入消息队列模块
import random #导入随机数模块,是为了模拟生产者与消费者速度不一致的情形
q = Queue.Queue() #实例化一个对象
def Producer(name): #生产者函数
for i in range( 20 ):
q.put(i) #将结果放入消息队列中
print '\033[32;1mProducer %s has made %s baozi....\033[0m' % (name, i)
time.sleep(random.randrange( 3 )) #生产者的生产速度,3s内
def Consumer(name): #消费者函数
count = 0
while count < 20 :
data = q. get () #取用消息队列中存放的结果
print '\033[31;1mConsumer %s has eatem %s baozi...chihuo...\033[0m' % (name, data)
count += 1
time.sleep(random.randrange( 4 )) #消费者的消费速度,4s内
p = threading.Thread(target = Producer, args = ( 'Alex' ,))
c = threading.Thread(target = Consumer, args = ( 'Wangfanhao' ,))
p.start()
c.start()
|