父亲儿子女儿放取水果进程/线程间通信程序设计与实现
代码:
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t onelock;
pthread_mutex_t twolock;
int mutex=1;//互斥
int count=0;//计数,记录放了多少个水果
int apple=0;//盘中苹果的个数
int orange=0;//盘中桔子的个数
int choice=0;//父亲选择放置桔子还是苹果
int number;//记录应该放置多少个水果
void wait()
{
//wait操作
pthread_mutex_lock(&onelock);
while(mutex<=0);
mutex=mutex-1;
pthread_mutex_unlock(&onelock);
}
void signal()
{
//signal操作
pthread_mutex_lock(&twolock);
while(mutex!=0);
mutex= mutex+1;
pthread_mutex_unlock(&twolock);
}
void *father()
{
while(1)
{
if(orange==0&&apple==0)
{
wait();
sleep(2);
if(choice==1)
{
orange=1;
printf("爸爸放置了一个桔子\n");
}
if(choice==2)
{
apple=1;
printf("爸爸放置了一个苹果\n");
}
choice=0;
count++;
signal();
}
if(count==number)
{
pthread_exit (NULL);
}
}
}
void *son()
{
while(1)
{
if(orange==1)
{
wait();
sleep(2);
orange=0;
choice=0;
printf("儿子从盘子中拿了一个桔子\n");
if(count!=number)
{
scanf("%d",&choice);
}
signal();
}
if(count==number&&orange!=1)
{
pthread_exit (NULL);
}
}
}
void *daughter()
{
while(1)
{
if(apple==1)
{
wait();
sleep(2);
apple=0;
choice=0;
printf("女儿从盘子中拿了一个苹果\n");
if(count!=number)
{
scanf("%d",&choice);
}
signal();
}
if(count==number&&apple!=1)
{
pthread_exit (NULL);
}
}
}
int main()
{
pthread_mutex_init(&onelock,NULL);
pthread_mutex_init(&twolock,NULL);
//父亲 女儿 儿子进程
pthread_t fatherThread;
pthread_t daughterThread;
pthread_t sonThread;
printf("请输入父亲放置水果的次数:");
scanf("%d",&number);
printf("请输入父亲放置的水果是什么,1为桔子,2为苹果: \n");
scanf("%d",&choice);
pthread_create(&fatherThread,NULL,father,NULL);
pthread_create(&daughterThread,NULL,daughter,NULL);
pthread_create(&sonThread,NULL,son,NULL);
pthread_join(fatherThread,NULL);
pthread_join(daughterThread,NULL);
pthread_join(sonThread,NULL);
}
运行结果: