现在的位置: 首页 > 综合 > 正文

PV生产者消费者问题

2018年04月29日 ⁄ 综合 ⁄ 共 438字 ⁄ 字号 评论关闭
#define N 100
typedef semaphore int;
semaphore muxtex = 1;    //临界区锁,用于防止生产者消费者同时访问临界资源 
semaphore full = 0;      //有面包的格子数 
semaphore empty = N;	 //没面包的格子数 

void consumer(void)
{
	int item;
	
	while(true)
	{
		P(full);         //P操作,尝试使用1张full通行证,若full空,去睡觉。 
		P(mutex);        //若能操作到这,说明有面包。
		item = get_item();//将面包拿下来。
		V(mutex);		 //关锁
		V(empty); 		 //发放1张空格子通行证 
	}
}

void producer(void)
{
	int item;
	
	while(true)
	{
		item = produce(); //生产一个面包
		P(empty);
		P(mutex);         //开锁
		insert_item(item) //将生产的面包放在格子上 
		V(mutex);         //关锁
		V(full);          //发放一张full通行证 
	}
}

抱歉!评论已关闭.