資源簡介
linux系統(tǒng)c語言實(shí)現(xiàn)爸爸兒子女兒簡單消費(fèi)者問題蘋果橘子拿與放問題,
資源共享,線程互斥,使用簡單的無名信號量解決
代碼片段和文件信息
#include
#include
#include
#include
#include
#include
sem_t?mutex?appleemptyorange;
void?*father(void?*arg)
{
while(1)
{
sem_wait(&empty);
sem_wait(&mutex);
srand((unsigned?int)time(NULL));
int?num=rand()%100+0;
if(num%2==0)
{
sem_post(&apple);
printf(“Father?produces?an?apple!\n“);
int?a;
sem_getvalue(&apple&a);
printf(“現(xiàn)在apple有:“a);
}
else
{
sem_post(&orange);
printf(“Father?produces?an?orange!\n“);
int?a;
sem_getvalue(&apple&a);
printf(“現(xiàn)在apple有:“a);
}
sem_post(&mutex);
sleep(1);
}
}
void?*son(void?*arg)
{
while(1)
{
sem_wait(&orange);
sem_wait(&mutex);
sem_post(&empty);
printf(“Son?consumes?an?orange!\n“);
sem_post(&mutex);
sleep(1);
}
}
void?*daughter(void?*arg)
{
whil
評論
共有 條評論