Question
Problem DescriptionIn this problem, you will implement a program where counter threads increment a shared variable. Since the counter threads do not have exclusive access
Problem DescriptionIn this problem, you will implement a program where counter threads increment a shared variable. Since the counter threads do not have exclusive access to the counter variable when accessing it, the race condition happens, and the variable is not incremented correctly. Follow the below instructions:
1.In the code, each of the placeholder comments should be replaced with one or more instructions in order to complete the program.
2.The required libraries have been added to the file, but you may need to include more libraries if you follow a different approach.
3.In the source file,the function count increments the shared variable globalNumberby one for 10 times. The program creates five threads that run the counter function,and therefore at the end,the value of the globalNumbervariable should be 50.
4.Modify your program to be a multi-module program. Create a Makefile, compile your program after by typing make, then execute the program. Use the script command to take a copy of all the output to the terminal.
The code given is below
#include
#include
#include
#include
#include
#include
#include
void * count(void *);
int globalNumber = 0;
//Create a mutex
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int main(void) {
int i;
pthread_t counterThread[5];
//Create the 5 threads
/* Wait for all treads to finish */
return (0);
}
void * count(void * junk) {
int loopCount = 0;
pthread_mutex_lock(&mutex1);
while (loopCount < 10) {
int tmpNumber = globalNumber;
printf("counter: %d, Thread: %ld, PID: %d ",
tmpNumber, pthread_self(), getpid());
tmpNumber = globalNumber;
tmpNumber++;
usleep(random() % 2);
globalNumber = tmpNumber;
loopCount++;
}
pthread_mutex_unlock(&mutex1);
return (0);
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started