熟睡的理发师问题描述的是多个进程(线程)之间的通信与同步问题:
有一个理发师的椅子,和n个顾客的椅子
如果有顾客在椅子上等,那么理发师为他剪发,否则理发师就在自己的椅子上睡觉。
如果理发师在熟睡,那么顾客会叫醒理发师,否则顾客会看有没有空椅子,有的话,他坐下等,否则,他将离开理发店。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#define MAX 10
#define TRUE 1
#define p(x) sem_wait(&x)
#define v(x) sem_post(&x)
sem_t customer,barber;
int chairs;
pthread_mutex_t mutex;
void init ( )
{
sem_init ( &customer , 0 , 0 );
sem_init ( &barber , 0 , 1 );
chairs = MAX;
}
void* _barber ( )
{
while ( TRUE )
{
p(customer);
pthread_mutex_lock(&mutex);
chairs++;
pthread_mutex_unlock(&mutex);
sleep(5);
printf ( "one work done....\n" );
v(barber);
}
}
void* _customer ( void* arg )
{
int *p = (int*) arg;
int x = *p;
pthread_mutex_lock(&mutex);
if ( chairs > 0 )
{
chairs--;
v(customer);
printf ( "the %dth customer sitting and waiting , %d customers wating...\n" , x , MAX-chairs );
pthread_mutex_unlock(&mutex);
p(barber);
}
else
{
pthread_mutex_unlock(&mutex);
printf ( "the %dth customer go away!\n" , x );
}
}
int main ( )
{
int i;
init ( );
pthread_t b;
pthread_t pthreads[MAX*100];
int cid[MAX*100];
pthread_create ( &b , NULL , _barber , NULL );
for ( i = 0 ; i < MAX*100 ; i ++ )
{
sleep(1);
cid[i] = i;
pthread_create ( &pthreads[i] , NULL , _customer , &cid[i] );
}
pthread_join ( b , NULL );
for ( i = 0 ; i < MAX*100 ; i++ )
pthread_join ( cid[i] , NULL );
}