理发师多线程实现

理发师问题的实现,多线程。

linux下运行

gcc ***.c -oxx -lpthread

#include <stdio.h>

#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/time.h>
#include <math.h>
#define CHAIRS 4


sem_t customers;//等待服务的顾客数
sem_t barbers;//等待顾客的理发师数
pthread_mutex_t mutex;//用于互斥
int waiting = 0;//等待的顾客
int if_no_more = 0;
void cut_hair()
{
printf("理发师:开始理发\n");
sleep(rand()%7 + 1);
}


void* barber()
{
    while(1)
    {
    if(waiting == 0)
    printf("理发师:当前没有顾客,睡觉\n");
        sem_wait(&customers);//如果没有顾客,理发师睡,进程阻塞
        pthread_mutex_lock(&mutex);//互斥进入临界区,欲修改waiting
        waiting--;//等待理发人数减一
        pthread_mutex_unlock( &mutex);//退出临界区,完成对waiting的修改
        cut_hair();//理发师理发
        sem_post(&barbers);//理发师结束理发barbers++
        sleep(rand()%2 + 1);
        if(if_no_more && waiting == 0)
        break;
    }
    sleep(3);
    printf("下班\n");
    return;
}
void* customer()
{
int color = rand()%5+32;
#define START "\033[1;%dm"
#define END "\033[0m"
    pthread_mutex_lock(&mutex);//互斥进入临界区,欲修改waiting
    if(waiting<CHAIRS)//如果有空椅子
    {
        waiting++;//等待理发的人数加1
        printf(START"新加了一位顾客%d\t等待理发人数:%d\n"END,color, (unsigned int)pthread_self(),waiting);
        pthread_mutex_unlock( &mutex);//退出临界区,完成对waiting的修改
        sem_post(&customers);//等待理发的人数加1,如有必要,唤醒理发师
        sem_wait(&barbers);//理发师是否空闲,若忙则阻塞barbers--
        printf(START"\t%d说:谢谢理发师。\n"END,color,(unsigned int)pthread_self());
    }
    else 
    {
    printf(START"%d说:没有空椅子了,我换一家\n"END,31,(unsigned int)pthread_self());
    pthread_mutex_unlock( &mutex);//没有空椅子,顾客离开
    }
    return;
}
int main()
{
int i;
pthread_t barber_id, customer_id;
sem_init(&customers, 0, 0);
    sem_init(&barbers, 0, 0);  
    pthread_mutex_init( &mutex, NULL);
    srand(time(0));
    pthread_create( &barber_id, NULL, barber, NULL);
    
    for(i=0; i<10;i++)
    {
    sleep(rand()%4 + 1);  
        pthread_create( &customer_id, NULL, customer, NULL); 
    }


    if_no_more = 1;//后面没有客户了
    pthread_join(barber_id,NULL);
    return 0;


}


猜你喜欢

转载自blog.csdn.net/yige__cxy/article/details/78880305