Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 /* printf */

#include /* pid_t */

#include /* get_pid */

#include /* exit, EXIT_FAILURE */

#include /* wait */

#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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Machine Learning And Knowledge Discovery In Databases European Conference Ecml Pkdd 2022 Grenoble France September 19 23 2022 Proceedings Part 4 Lnai 13716

Authors: Massih-Reza Amini ,Stephane Canu ,Asja Fischer ,Tias Guns ,Petra Kralj Novak ,Grigorios Tsoumakas

1st Edition

3031264118, 978-3031264115

More Books

Students also viewed these Databases questions