Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<pthread.h>
- #include<semaphore.h>
- #include<unistd.h>
- #include<queue>
- using namespace std;
- #define MAX 20
- #define MAX_B 3
- pthread_t Booth_T[MAX_B+7];
- pthread_t HeadC_T;
- queue<long> Booth_Q[MAX_B+7];
- queue<long> HeadC_Q;
- pthread_mutex_t Booth_LK[MAX_B+7];
- pthread_mutex_t HeadC_LK;
- sem_t Booth_SM[MAX_B+7];
- sem_t Customer_SM[MAX+7];
- sem_t Empty;
- sem_t Full;
- void* Customer_Func( void *Arg )
- {
- long Nm = *((long*)Arg);
- long b = rand()%MAX_B;
- printf("Customer %ld: Has come to booth %ld\n",Nm,b );
- sem_init( &Customer_SM[Nm],0,0 );
- pthread_mutex_lock( &Booth_LK[b] );
- Booth_Q[b].push( Nm );
- sem_post( &Booth_SM[b] );
- pthread_mutex_unlock( &Booth_LK[b] );
- sem_wait( &Customer_SM[Nm] );
- printf("Customer %ld: Gone home\n",Nm );
- }
- void* Booth_Func( void *Arg )
- {
- long b = *((long*)Arg);
- while(1){
- sem_wait( &Booth_SM[b] );
- pthread_mutex_lock( &Booth_LK[b] );
- long Nm = Booth_Q[b].front();
- Booth_Q[b].pop();
- printf("Customer %ld: In booth %ld cashier has collected the money and signed the receipt\n",Nm,b );
- sleep(1);
- pthread_mutex_unlock( &Booth_LK[b] );
- sem_wait( &Empty );
- pthread_mutex_lock( &HeadC_LK );
- HeadC_Q.push( Nm );
- printf("Customer %ld: In booth %ld cashier has passed the receipt to the head cashier\n",Nm,b );
- sem_post( &Full );
- pthread_mutex_unlock( &HeadC_LK );
- }
- }
- void* HeadC_Func( void* Arg ){
- while(1){
- sem_wait( &Full );
- pthread_mutex_lock( &HeadC_LK );
- long Nm = HeadC_Q.front();
- HeadC_Q.pop();
- printf("customer %ld: Head Cashier has received the receipt , given initial and passed back to customer\n",Nm );
- pthread_mutex_unlock( &HeadC_LK );
- sem_post( &Empty );
- sem_post( &Customer_SM[Nm] );
- sleep(1);
- }
- }
- int main(void)
- {
- long i;
- for( i=0;i<MAX_B;i++ ){
- long *p = new long;
- *p = i;
- pthread_create( &Booth_T[i],NULL,Booth_Func,(void*)p );
- sem_init( &Booth_SM[i],0,0 );
- pthread_mutex_init( &Booth_LK[i],0 );
- }
- pthread_create( &HeadC_T,NULL,HeadC_Func,NULL );
- sem_init( &Empty,0,5 );
- sem_init( &Full,0,0 );
- long Ct = 1;
- while( Ct<=MAX ){
- long *p = new long;
- *p = Ct;
- pthread_create( new pthread_t,NULL,Customer_Func,(void*)p );
- Ct++;
- }
- for( i=0;i<MAX_B;i++ ){
- pthread_join( Booth_T[i],NULL );
- }
- pthread_join( HeadC_T,NULL );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement