#include sem_t empty; //定义信号量
sem_t applefull;
sem_t orangefull;
void *procf(void *arg) //father线程
{
while(1){
sem_wait(&empty); //P操作
printf("%s\n",(char *)arg);
sem_post(&applefull); //V操作
sleep(7);
}
}
void *procm(void *arg) //mother线程
{
while(1){
sem_wait(&empty);
printf("%s\n",(char *)arg);
sem_post(&orangefull);
sleep(3);
}
}
void *procs(void *arg) //son线程
{
while(1){
sem_wait(&orangefull);
printf("%s\n",(char *)arg);
sem_post(&empty);
sleep(2);
}
}
void *procd(void *arg) //daughter线程
{
while(1){
sem_wait(&applefull);
printf("%s\n",(char *)arg);
sem_post(&empty);
sleep(5);
}
}
main()
{
pthread_t father; //定义线程
pthread_t mother;
pthread_t son;
pthread_t daughter;
sem_init(&empty, 0, 1); //信号量初始化
sem_init(&applefull, 0, 0);
sem_init(&orangefull, 0, 0);
pthread_create(&father,NULL,procf,"father input an apple."); //创建线程
pthread_create(&mother,NULL,procm,"mother input an orange.");
pthread_create(&daughter,NULL,procd,"daughter get an apple.");
pthread_create(&son,NULL,procs,"son get an orange.");
while(1){} //循环等待
}
另外,站长团上有产品团购,便宜有保证