Question: sing counting semaphores can simplify thread synchronization , in particular, when some resource that has multiple instances. In the following example, 16 concurrent threads (executing

sing counting semaphores can simplify thread synchronization, in particular, when some resource that has multiple instances.

In the following example, 16 concurrent threads (executing the run function) attempt to access 4 virtual printers. We use a counting semaphore initialized to 4 in order to represent the number of available printers.

Each thread will do the following, forever:

Try and obtain an available printer

Sleep for a random number of seconds (This simulates using the printer.)

Release the printer

Sleep for a random number of seconds (This simulates other actions of a typical thread before needing the printer again.)

Threads will simply be use Decrement and Wait before accessing a printer and Increment and Signal when they have finished using a printer.

Create the file: counting_semaphore.c

#include

#include

#include //compile and link with -pthread

#include

const int NUM_THREADS = 16;

const int NUM_PRINTERS = 4;

sem_t s;

void *run( void *ptr ) {

int tid = (int) pthread_self();

int value;

while(1){

printf("%d needs a printer now! ", tid);

sem_getvalue(&s, &value);

printf("\tsemaphore value = %d ", value);

sem_wait(&s);

printf("%d is printing now! ", tid);

usleep(rand() % 1000);

printf("%d is done printing! ", tid);

sem_getvalue(&s, &value);

printf("\tsemaphore value = %d ", value);

sem_post(&s);

printf("%d is doing something else... ", tid);

usleep(rand() % 1000);

}

}

int main() {

pthread_t threads[NUM_THREADS];

sem_init(&s, 0, NUM_PRINTERS);

srand(time(NULL));

int i;

for(i = 0; i < NUM_THREADS; i++){

pthread_create( &threads[i], NULL, run, NULL);

}

for(i = 0; i < NUM_THREADS; i++){

pthread_join( threads[i], NULL);

}

exit(0);

}

Compile the file:

student@Ubuntu:~/labs/lab3$ gcc -pthread counting_semaphore.c -o cs

Run the counting_semaphore program for a few seconds. Then press <Ctrl+ C> to stop the program:

student@Ubuntu:~ /labs/lab3 $ ./cs

Copy and paste the output below. Check the output for any inconsistency.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!