#include<stdio.h> 
#include<pthread.h>
 #include<semaphore.h>
 sem_t semaphore; 
void* process(void* arg) {   
  sem_wait(&semaphore); 
  printf("Process %d is in critical section\n", *(int*)arg);      
 sleep(1); // simulate work      
printf("Process %d is leaving critical section\n", *(int*)arg); sem_post(&semaphore);   
return NULL; 
} 
int main() {   
  pthread_t t1, t2;    
 int id1 = 1, id2 = 2;   
  sem_init(&semaphore, 0, 1);  
  pthread_create(&t1, NULL, process, &id1);   
  pthread_create(&t2, NULL, process, &id2);     
  pthread_join(t1, NULL);     
  pthread_join(t2, NULL);    
  sem_destroy(&semaphore); 
    return 0;  
    
} 
 
