Produce-Consumer Problem

Posted 幻觉czw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Produce-Consumer Problem相关的知识,希望对你有一定的参考价值。

# -*- encoding: utf8 -*-
from threading import Thread, Condition
from Queue import Queue
import time
import random

CONDITION = Condition()

class Pool(Queue):
	"""
	模拟一个能存放固定数目的值的缓存区
	"""

	def __init__(self, maxsize):
		Queue.__init__(self)
		self.length = 0
		self._maxsize = maxsize

	def get(self):
		if self.length == 0:
			raise Exception("The pool is empty!")
		self.length -= 1
		return Queue.get(self)

	def put(self, value):
		if self.length == self._maxsize:
			raise Exception("The pool is full!")
		self.length += 1
		Queue.put(self, value)

	def empty(self):
		if self.length == 0:
			return True
		return False

	def full(self):
		if self.length == self._maxsize:
			return True
		return False


class Producer(Thread):
	"""
	模拟生产者,每次生产一个值放入缓存区,如果缓存区
	为满就停止生产
	"""

	def __init__(self, queue):
		Thread.__init__(self)
		self.pool = queue

	def 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 : ', temp
				CONDITION.notify() #唤醒Consumer,但notify()并未释放锁

			CONDITION.release()#释放锁让Consumer运行
			time.sleep(1)


class Consumer(Thread):
	"""
	模拟消费者,每次处理两个值
	"""

	def __init__(self, queue):
		Thread.__init__(self)
		self.pool = queue

	def 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()

以上是关于Produce-Consumer Problem的主要内容,如果未能解决你的问题,请参考以下文章

uva10401Injured Queen Problem(递推)

E - The Blocks Problem ( UVA - 101)

木块问题 The Blocks Problem, UVa 101

knapsack problem 背包问题 贪婪算法GA

UVa 101 - The Blocks Problem STL

1192:放苹果