采用随机数生成父亲放置的水果。
单数表示父亲放置的是苹果,由女儿来取
双数表示父亲放置的是橘子,由儿子来取
进程采用一直循环执行的方式
#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "unistd.h"
#include "semaphore.h"
sem_t empty;
sem_t apple;
sem_t orange; // 1 define
void *father(void *var){
while(1)
{
sem_wait(&empty);//sleep
int number=rand();
if(number%2==0)
{
printf("father put an orange\n");
sem_post(&orange);
}
else{
printf("father put an apple\n");
sem_post(&apple);
}
}
}
void *son(void *var){
while(1){
sem_wait(&orange);
printf("son get an orange\n");
sem_post(&empty);
}
}
void *daughter(void *var){
while(1){
sem_wait(&apple);
printf("daughter get an apple\n");
sem_post(&empty);
}
}
int main(){ // main thread
pthread_t tid;
int ret;
char str[] = " hello linux\n";
sem_init(&empty,0,1);// 2 init
sem_init(&apple,0,0);
sem_init(&orange,0,0);
pthread_create(&tid,NULL,father,(void *)str);
pthread_create(&tid,NULL,son,(void *)str);
pthread_create(&tid,NULL,daughter,(void *)str);
while (1);
return 0;
}
运行结果如下: