I want the threads to access the critical section randomaly, currently they just access it one by one, first thread 0 then thread 1 then thread 2...., how can i get some context switching going on in here using semaphores.Code:/* Includes */ #include <unistd.h> /* Symbolic Constants */ #include <sys/types.h> /* Primitive System Data Types */ #include <errno.h> /* Errors */ #include <stdio.h> /* Input/Output */ #include <stdlib.h> /* General Utilities */ #include <pthread.h> /* POSIX Threads */ #include <string.h> /* String handling */ #include <semaphore.h> /* Semaphore */ #include <time.h> /* prototype for thread routine */ void handler ( void *ptr ); void producer ( void *ptr ); /* global vars */ /* semaphores are declared global so they can be accessed in main() and in thread routine, here, the semaphore is used as a mutex */ sem_t mutex; int counter=0; /* shared variable */ int main() { int i; pthread_t prod[1000]; sem_init(&mutex, 0, 1); /* initialize mutex to 1 - binary semaphore */ /* second param = 0 - semaphore is local */ srand((unsigned)time(NULL)); for(i=0; i<1000; i++) { pthread_create (&prod[i], NULL, producer, (void *) &i); pthread_join (prod[i], NULL); } sem_destroy(&mutex); /* destroy semaphore */ return(0); } void producer ( void *ptr ) { int x; int c; int z; int b; b = (rand() & 255); z = *((int *) ptr); for(x=0; x<b; x++) { if( (rand() & 1) == 0) { handler(&z); // for(c=0; c<1000000; c++) // { // } } } } void handler ( void *ptr ) { int x; x = *((int *) ptr); // printf("Thread %d: Waiting to enter critical region...\n", x); sem_wait(&mutex); /* down semaphore */ /* START CRITICAL REGION */ // printf("Thread %d: Now in critical region...\n", x); // printf("Thread %d: Counter Value: %d\n", x, counter); // printf("Thread %d: Incrementing Counter...\n", x); counter++; printf("Thread %d: New Counter Value: %d\n", x, counter); // printf("Thread %d: Exiting critical region...\n", x); /* END CRITICAL REGION */ sem_post(&mutex); /* up semaphore */ // pthread_exit(0); /* exit thread */ }