#include<stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <unistd.h>
void father();
void daughter();
sem_t empty,app; //定义信号量empty, app ;
int k=0; //盘中苹果个数
int main()
{ pthread_t th1,th2;
int ret;
sem_init(&empty,0,1); //初始化线程信号量empty ,初值为1
sem_init(&app,0,0); //初始化线程信号量app ,初值为0
ret=pthread_create(&th1,NULL,(void *) father, NULL);
if(ret!=0) perror("pthread cread1");
ret=pthread_create(&th2,NULL,(void *)daughter, NULL);
if(ret!=0) perror("pthread cread2");
pthread_join(th1,NULL);
pthread_join(th2,NULL);
return 0;
}
void father()
{
do{
//执行信号量empty的wait()操作,相当于 wait(empty)
sem_wait(& empty);
printf("I am father\n");
printf("I am putting an apple in the plate!\n");
printf("There is %d fruit in the plate!\n",++k);
//执行信号量app的signal()操作,相当于 signal(app)
sem_post(& app);
}while(1);
}
void daughter()
{
do{
//执行信号量app的wait()操作,相当于 wait(app)
sem_wait(&app);
printf("I am daughter\n");
printf("I am picking an apple from the plate!\n");
printf("There are %d fruit in the plate!\n",--k);
//执行信号量empty的signal()操作,相当于signal(empty)
sem_post(& empty);
}while(1);
}
pv-signal1.c
最新推荐文章于 2024-07-25 13:40:37 发布