#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t empty;
sem_t apple;
sem_t orange;
pthread_mutex_t work_mutex=PTHREAD_MUTEX_INITIALIZER;
int fruitCount = 0;
void *procf(void *arg)
{
while(1){
sem_wait(&empty);
pthread_mutex_lock(&work_mutex);
printf("爸爸放入一个苹果!(盘子当前水果总数:%d)\n", ++fruitCount);
sem_post(&apple);
pthread_mutex_unlock(&work_mutex);
sleep(0.1);
}
}
void *procm(void *arg)
{
while(1){
sem_wait(&empty);
pthread_mutex_lock(&work_mutex);
printf("妈妈放入一个橙子!(盘子当前水果总数:%d)\n", ++fruitCount);
sem_post(&orange);
pthread_mutex_unlock(&work_mutex);
sleep(0.2);
}
}
void *procs(void *arg)
{
while(1){
sem_wait(&apple);
pthread_mutex_lock(&work_mutex);
printf("儿子吃了一个苹果!(盘子当前水果总数:%d)\n", --fruitCount);
sem_post(&empty);
pthread_mutex_unlock(&work_mutex);
sleep(0.2);
}
}
void *procd(void *arg)
{
while(1){
sem_wait(&orange);
pthread_mutex_lock(&work_mutex);
printf("女儿吃了一个橙子!(盘子当前水果总数:%d)\n", --fruitCount);
sem_post(&empty);
pthread_mutex_unlock(&work_mutex);
sleep(0.1);
}
}
int main()
{
pthread_t father;
pthread_t mother;
pthread_t son;
pthread_t daughter;
sem_init(&empty, 0, 3);
sem_init(&apple, 0, 0);
sem_init(&orange, 0, 0);
pthread_create(&father,NULL,procf,NULL);
pthread_create(&mother,NULL,procm,NULL);
pthread_create(&daughter,NULL,procd,NULL);
pthread_create(&son,NULL,procs,NULL);
sleep(1);
sem_destroy(&empty);
sem_destroy(&apple);
sem_destroy(&orange);
return 0;
}