Chinaunix首页 | 论坛 | 博客
  • 博客访问: 266953
  • 博文数量: 103
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 705
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-02 16:15
文章分类

全部博文(103)

文章存档

2014年(8)

2013年(95)

我的朋友

分类: Python/Ruby

2013-12-19 14:43:54

import time
from threading import Thread,Condition,currentThread
class Goods:
        def __init__(self):
                self.count=0
        def produce(self,num=1):
                self.count =self.count+num
        def consume(self):
                if self.count:
                        self.count =self.count-1
        def isEmpty(self):
                return not self.count


class Producer(Thread):
        def __init__(self,condition,goods,sleeptime=1):
                Thread.__init__(self)
                self.cond = condition
                self.goods = goods
                self.sleeptime = sleeptime


        def run(self):
                cond = self.cond
                goods = self.goods
                while True:
                        cond.acquire()
                        goods.produce()
                        print "Goods CountL",goods.count,"Producer thread produced"
                        cond.notifyAll()
                        cond.release()
                        time.sleep(self.sleeptime)


class Consumer(Thread):
        def __init__(self,index,condition,goods,sleeptime=4):
                Thread.__init__(self,name=str(index))
                self.cond=condition
                self.goods=goods
                self.sleeptime=sleeptime
        def run(self):
                cond=self.cond
                goods=self.goods
                while True:
                        time.sleep(self.sleeptime)
                        cond.acquire()
                        while goods.isEmpty():
                                cond.wait()
                        goods.consume()
                        print "Goods Count:",goods.count,"Consumer thread",currentThread().getName(),"consumed"
                        cond.release()


goods=Goods()
cond=Condition()


producer=Producer(cond,goods)
producer.start()
#producer.join()
for i in range(5):
        consumer=Consumer(i,cond,goods)
        consumer.start()
#       consumer.join()


阅读(1131) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~