Linux 同步理发师问题

熟睡的理发师问题描述的是多个进程(线程)之间的通信与同步问题:

有一个理发师的椅子,和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 );
}

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌上花开缓缓归以

你的鼓励将是我创作的最大动力,

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值