Question: Program 1 Given the following program called critSec.c that has a critical section where a shared counter is updated #include #include #define NUM _ THREADS
Program
Given the following program called critSec.c that has a critical section where a shared counter is updated
#include
#include
#define NUMTHREADS
#define ITERATIONS
int counter ; Shared counter
void incrementvoid arg
for int i ; i ITERATIONS; i
Critical section: increment the shared counter
counter;
return NULL;
int main
pthreadt threadsNUMTHREADS;
Create threads
for int i ; i NUMTHREADS; i
pthreadcreate&threadsi NULL, increment, NULL;
Wait for all threads to finish
for int i ; i NUMTHREADS; i
pthreadjointhreadsi NULL;
printfFinal counter value: d
counter;
return ;
Start by compiling and running this program. The correct value for the Final Counter should be iterations done by threads. You will find that the output for Final Counter value will vary a fair bit. This is due to timing errors and a race condition.
Next copy the program to one called critSecMutex.c where you will add a mutex to protect the critical section.
Finally, make another copy of the critSec.c and cally it critSecSemaphore.c where you add a semaphore to protect the critical section.
Program
Start with the following c program that has the same race condition as about:
#include
#include
#include
using namespace std;
const int ITERATIONS ;
int counter ; Shared resource
void increment
for int i ; i ITERATIONS; i
Critical section: incrementing the counter
counter;
int main
vector threads;
Create multiple threads
for int i ; i ; i
threads.pushbackthreadincrement;
Wait for all threads to finish
for auto& th : threads
thjoin;
cout "Final counter value: counter endl;
return ;
Save this as critSec.cpp Do the same as before and compile and run this to verify that the final count does in fact give different results.
Then create a copy called critSecMonitor.cpp and protect the critical section with a Monitor class.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
