设为首页 加入收藏

TOP

基于toyix的进程和轻权进程的学习(四)
2017-01-02 08:15:12 】 浏览:895
Tags:基于 toyix 进程 学习
],in);
in=(in+1)%10;
v(&s);
v(&full);
}
}
consumer()
{
int out=0;
while(1)
{
delay(400);
p(&full);
p(&s);
printf("Consumer: There are %d products in NO.%d buffer\n",--product[out],out);
out=(out+1)%10;
v(&s);
v(&empty);
}
}
main()
{
set(&s,1);
set(&empty,20);
set(&full,0);
cobegin(producer,consumer,0);
getch();
}


(3)一组生产者、一组消费者,公用n个环形缓冲区


因为有多个生产者和多个消费者,生产者之间存在互斥关系,消费者之间也存在互斥关系。所以我们要用信号量来控制一个时间只能有一个生产者在生产,一个消费者在消费。所以我们设mutex1为生产者之间的互斥信号量,初值为1,mutex2为消费者之间的互斥信号量,初值为2.,


程序如下:


#include


semaphore s,empty,full,mutex1,mutex2;


int product[10]={0};


producer()


{


int in=0;


while(1)


{


delay(20);


p(&empty);


p(&mutex1);


p(&s);


printf("Producer: There are %d products in NO.%d buffer\n",++product[in],in);


in=(in+1)%10;


v(&s);


v(&mutex1);


v(&full);


}


}


consumer()


{


int out=0;


while(1)


{


delay(400);


p(&full);


p(&mutex2);


p(&s);


printf("Consumer: There are %d products in NO.%d buffer\n",--product[out],out);


out=(out+1)%10;


v(&s);


v(&mutex2);


v(&empty);


}


}


main()


{


set(&s,1);


set(&empty,20);


set(&full,0);


set(&mutex1,1);


set(&mutex2,1);


cobegin(producer,consumer,0);


getch();


}


首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇配置TC2.0运行环境 下一篇高级语言里的函数在汇编里的实现..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目