// Demo of Semaphores in C #include #include #include #include sem_t mutex; void* thread(void* arg) { //wait sem_wait(&mutex); printf("\n Thread Entering..\n"); //critical section printf("In critical section"); sleep(4); //signal printf("\n Thread Exiting...\n"); sem_post(&mutex); return 0; } int main() { sem_init(&mutex, 0, 1); pthread_t t1,t2; pthread_create(&t1,NULL,thread,NULL); // runs thread method on creation printf("\n Thread 1 ID: %i", t1); sleep(2); pthread_create(&t2,NULL,thread,NULL); // runs thread method on creation printf("\n Thread 2 ID: %i", t2); pthread_join(t1,NULL); pthread_join(t2,NULL); sem_destroy(&mutex); return 0; }