Question: Write a C program, thrIncr , that creates two threads, each of which executes the same function. The function, threadFunc() , executes a loop that
Write a C program, thrIncr, that creates two threads, each of which executes the same function. The function, threadFunc(), executes a loop that repeatedly increments a global variable, counter, by copying counter into the local variable, loc, incrementing loc, and copying loc back to counter. (Since loc is an automatic variable allocated on the pthread stack, each thread has its own copy of this variable.) The number of iterations of the loop is determined by the command-line argument supplied to the program, or by a default value (10,000,000) if no argument is supplied.
Run the program first by specifying the value 1000 as the number of iterations of the loop. Capture the output. The second run of the program uses the default value for the number of iterations of the loop. Capture the output. Do the outputs in both the runs look correct?
To avoid the problems that can occur when threads try to update a shared variable, we must use a mutex to ensure that only one thread at a time can access the variable. Modify the program to protect the critical section by a mutex. Run the program twice again as before, first by using a value of 1000 for the number of iterations and then by using the default value. Capture both outputs. What changes in the outputs do you see after using the mutex?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
