Produce-Consumer Problem

来源:互联网 发布:淘宝阿尔法软件 编辑:程序博客网 时间:2024/06/07 07:50
# -*- encoding: utf8 -*-from threading import Thread, Conditionfrom Queue import Queueimport timeimport randomCONDITION = Condition()class Pool(Queue):"""模拟一个能存放固定数目的值的缓存区"""def __init__(self, maxsize):Queue.__init__(self)self.length = 0self._maxsize = maxsizedef get(self):if self.length == 0:raise Exception("The pool is empty!")self.length -= 1return Queue.get(self)def put(self, value):if self.length == self._maxsize:raise Exception("The pool is full!")self.length += 1Queue.put(self, value)def empty(self):if self.length == 0:return Truereturn Falsedef full(self):if self.length == self._maxsize:return Truereturn Falseclass Producer(Thread):"""模拟生产者,每次生产一个值放入缓存区,如果缓存区为满就停止生产"""def __init__(self, queue):Thread.__init__(self)self.pool = queuedef run(self):while True:CONDITION.acquire()if self.pool.full():print 'Producer : I will sleep...'CONDITION.wait() #Producer挂起,同时释放Consumer的线程锁print 'Produce : I woke up...'if not self.pool.full():temp = random.randint(0,100)self.pool.put(temp)print 'Producer : I produce a value : ', tempCONDITION.notify() #唤醒Consumer,但notify()并未释放锁CONDITION.release()#释放锁让Consumer运行time.sleep(1)class Consumer(Thread):"""模拟消费者,每次处理两个值"""def __init__(self, queue):Thread.__init__(self)self.pool = queuedef run(self):while True:CONDITION.acquire()if self.pool.length < 2: print 'Consumer: I will sleep...'CONDITION.wait()print 'Consumer : I woke up...'if self.pool.length >= 2:temp1 = self.pool.get()temp2 = self.pool.get()print 'Consumer : I will handle %s and %s' % (temp1, temp2)CONDITION.notify()CONDITION.release()time.sleep(3)def test():buffer_pool = Pool(10)producer = Producer(buffer_pool)consumer = Consumer(buffer_pool)producer.start()consumer.start()if __name__ == '__main__':test()

0 0
原创粉丝点击