#include <pthread.h>#include<semaphore.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>#include<cerrno>#defineCustomer_num 10pthread_mutex_t mutex_x=pthread_mutex_initializer;sem_t sem;intSem_val =0;intIRet;void* Get_service (void*thread_id) { intcustomer_id = * ((int*) thread_id); if(sem_wait (&sem) = =0) {Sem_getvalue (&sem, &sem_val); //printf ("\ n");printf ("....... Available Windows--%d ... \ n", sem_val+1); IRet=pthread_mutex_trylock (&mutex_x); if(iret==ebusy) {printf ("window is occupied please replace the service window. \ n"); }Else if(iret==0) {printf ("Customer%d receive service ... \ n", customer_id); Usleep ( +);/*Service time:100ms*/printf ("Customer%d receive service over\n", customer_id); Pthread_mutex_unlock (&mutex_x); } sem_post (&SEM); }}intMainintargcChar*argv[]) {Sem_init (&sem,0,2); pthread_t Customers[customer_num]; intI, IRet; for(i =0; i < Customer_num; i++){ intcustomer_id =i; IRet= Pthread_create (&customers[i], NULL, Get_service, &customer_id); if(IRet) {perror ("pthread_create"); returnIRet; } Else{printf ("Customer%d arrived.\n", i); } usleep ( $); } intJ; for(j =0; J < Customer_num; J + +) {pthread_join (customers[j], NULL); } Sem_destroy (&SEM); return 0;}
Multithreaded programming: Simultaneous use of semaphores and mutexes