Consider this variable x as critical section. That is : many threads will compete to update this variable.

int x = 80;

pthread_mutex_t one_lock = PTHREAD_MUTEX_INITIALIZER;

declare three functions

void * add1 ( void *a )

{

add code with mutex to increment x by *a and unlock the mutex

}

void * add2 ( void *b )

{

add code with mutex to increment x by b unlock the mutex

}

void * add3 ( void *c )

{

add code with mutex to increment x by c unlock the mutex

}

in the main function:

Create three threads using create function :

pthread_t t1, t2, t3 ;

int x1 = 10, x2 = 20, x3 = 30;

while creating thread t1, pass add1 function and variable x1

while creating thread2, pass add2 function and variable x2

while creating thread3, pass add3 function and variable x3

wait for the threads to terminate

print the value of x now

Sample Solution

This question has been answered.

Get Answer