模拟这个游戏:
有一个空盘子一次只能放入一个水果。爸爸放入一个橙子,只有女儿会拿起来吃。妈妈放入一个苹果,只有儿子会拿起来吃。
依次生成这4个线程,利用信号量来同步这4个线程,利用互斥锁来解决爸爸和妈妈争用空盘子的冲突,防止死锁。
当儿子一共吃过8个苹果时,结束整个游戏。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/time.h>
#include <math.h>
int order=1;
sem_t empty;
sem_t orange;
sem_t apple;
pthread_mutex_t mutex;
void* dad(void *xxx)
{
while(1)
{
sleep(rand()%5); /* get orange into hands */
sem_wait( &empty);
pthread_mutex_lock( &mutex);
printf("\n<%d>\ndad: put orange\n", order++);
pthread_mutex_unlock( &mutex);
sem_post( &orange);
}
return;
}
void* mom(void *xxx)
{
while(1)
{
sleep(rand()%5); /* get apple into hands */
sem_wait( &empty);
pthread_mutex_lock( &mutex);
printf("\n<%d>\nmom: put apple\n", order++);
pthread_mutex_unlock( &mutex);
sem_post( &apple);
}
return;
}
void* son(void *xxx)
{
int i=0;
while( ++i < 9)
{
sem_wait( &apple);
printf("son: got apple\n");
sem_post( &empty);
sleep(rand()%2); /* eating */
}
return;
}
void* daughter(void *xxx)
{
while(1)
{
sem_wait( &orange);
printf("daughter: got orange\n");
sem_post( &empty);
sleep(rand()%2); /* eating */
}
return;
}
int main()
{
pthread_t dad_id, mom_id, son_id, daughter_id;
sem_init(&empty, 0, 1);
sem_init(&apple, 0, 0);
sem_init(&orange, 0, 0);
pthread_mutex_init( &mutex, NULL);
srand(time(0));
pthread_create( &dad_id, NULL, dad, NULL);
pthread_create( &mom_id, NULL, mom, NULL);
pthread_create( &son_id, NULL, son, NULL);
pthread_create( &daughter_id, NULL, daughter, NULL);
pthread_join( son_id, NULL);
sem_destroy( &empty);
sem_destroy( &apple);
sem_destroy( &orange);
pthread_mutex_destroy( &mutex);
return 0;
}