[c]代码库
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<fcntl.h>
#include<errno.h>
#define n 5 //有五把椅子
//三个信号量: mutex,customer,barbers
sem_t mutex,customers,barbers;
int waiting=0; //等待的顾客数量
int chair[5];
void * barber();
void * customer ( void *arg );
int main ( int argc,char *argv[] )
{
//创建10个顾客和1个理发师
pthread_t Customer_id[10],Barber_id;
int i;
sem_init ( &mutex,0,1 ); //互斥信号量初始化1
sem_init ( &customers,0,0 );//顾客信号量初始化0
sem_init ( &barbers,0,1 );//理发师信号量初始化1
for ( i=0; i<5; i++ )
pthread_create ( &Barber_id,NULL, ( void* ) barber,NULL );
for ( i=0; i<10; i++ )
pthread_create ( &Customer_id[i],NULL, ( void* ) customer, ( void* ) ( i+1 ) );
for ( i=0; i<10; i++ )
pthread_join ( Customer_id[i],NULL );
for ( i=0; i<5; i++ )
pthread_join ( Barber_id,NULL );
return 0;
}
//创建理发师线程
void * barber()
{
int i;
int next;
//等待顾客,如果没有顾客,理发师睡觉
sem_wait ( &customers );
sem_wait ( &mutex ); //等待互斥锁释放
waiting--; //等待的顾客减1
for ( i=0; i<5; i++ )
{
if ( chair[i]!=0 )
{
next= chair[i];
chair[i]=0;
break;
}
}
printf ( "The barber is cutting %dth customer's hair\n",next );
sleep ( 3 );
sem_post ( &mutex );
sem_post ( &barbers );
}
//创建顾客线程
void * customer ( void *arg )
{
int i;
sem_wait ( &mutex ); //等待互斥锁释放
if ( waiting<n )
{
waiting++; //等待的顾客加1
for ( i=0; i<5; i++ )
{
if ( chair[i]==0 )
{
chair[i]= ( int ) arg;
break;
}
}
printf ( "***************************************************\n" );
printf ( "Entered:Number %d customer comes,and sits at %d chair \n", ( int ) arg, ( i+1 ) );
printf ( "There are %d customer on the chair\n",waiting );
printf ( "The customers' location are:" );
for ( i=0; i<5; i++ )
printf ( "%d ",chair[i] );
printf ( "\n" );
sleep ( 1 );
sem_post ( &mutex ); //释放互斥锁
sem_post ( &customers );
sem_wait ( &barbers ); //理发师等待
}
else
{
printf ( "Number %d comes,there are no chairs,the customer %d is leaving\n", ( int ) arg, ( int ) arg );
sem_post ( &mutex );
}
}