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 1
Given the following program called critSec.c that has a critical section where a shared counter is updated
#include
#include
#define NUM_THREADS 10
#define ITERATIONS 1000000
int counter =0; // Shared counter
void* increment(void* arg){
for (int i =0; i < ITERATIONS; i++){
// Critical section: increment the shared counter
counter++;
}
return NULL;
}
int main(){
pthread_t threads[NUM_THREADS];
// Create threads
for (int i =0; i < NUM_THREADS; i++){
pthread_create(&threads[i], NULL, increment, NULL);
}
// Wait for all threads to finish
for (int i =0; i < NUM_THREADS; i++){
pthread_join(threads[i], NULL);
}
printf("Final counter value: %d
", counter);
return 0;
}
Start by compiling and running this program. The correct value for the Final Counter should be 10,000,000(1,000,000 iterations done by 10 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 2
Start with the following c++ program that has the same race condition as about:
#include
#include
#include
using namespace std;
const int ITERATIONS =1000000;
int counter =0; // Shared resource
void increment(){
for (int i =0; i < ITERATIONS; i++){
// Critical section: incrementing the counter
counter++;
}
}
int main(){
vector threads;
// Create multiple threads
for (int i =0; i <10; i++){
threads.push_back(thread(increment));
}
// Wait for all threads to finish
for (auto& th : threads){
th.join();
}
cout << "Final counter value: "<< counter << endl;
return 0;
}
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 blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!