问题描述:
熟睡的理发师问题描述的是多个进程(线程)之间的通信与同步问题:
- 有一个理发师的椅子,和n个顾客的椅子
- 如果有顾客在椅子上等,那么理发师为他剪发,否则理发师就在自己的椅子上睡觉。
- 如果理发师在熟睡,那么顾客会叫醒理发师,否则顾客会看有没有空椅子,有的话,他坐下等,否则,他将离开理发店。
问题分析:
- 首先是避免死锁,也就是理发师一直在睡觉,所以我们采取让顾客叫醒理发师的方式,只要理发师一空闲下来,等待的顾客就会叫醒理发师。
- 因为顾客的座位是顾客进程(线程)共享的,所以要防止发生冲突
基本思路:
利用信号量来解决这个问题:
- 首先顾客的座位被所有顾客进程(线程)共享,所以要设置互斥量mutex,来防止多个进程(线程)同时修改内存造成的错误
- 理发师只有一个,所以需要设置信号量,来让顾客判断何时叫醒理发师。
- 顾客可以最多有座位个,需要设置信号量,让理发师判断是否去睡觉。
- 顾客会在获得互斥锁后,查看剩余座位数,来决定走或者留
为了简单,下面采取线程的方式实现
代码如下:
#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 );
}