熟睡的理发师问题描述的是多个进程(线程)之间的通信与同步问题:
有一个理发师的椅子,和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 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 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 );
}
本文发布于:2024-02-01 09:52:00,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170675232035797.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |