Question: Synchronization using Pthreads mutex The program below is used by two threads to modify/update a shared resource (a long integer) at the same time. There
- Synchronization using Pthreads mutex
The program below is used by two threads to modify/update a shared resource (a long integer) at the same time. There is no synchronization performed in the code below. You may see unexpected/unmathcing results when you execute the program multiple times. The shared resource is a long integer where first thread takes its value as 1 and increments it to a number 300 million, where the second thread decrements one from the incremented resource to all the way to 0 (but adding a -1 in the for loop). You will implement mutual exclusion in the code below to make sure that the increments and decrements of the shared resource are done without any interruption by the other thread.
/*
Compile: gcc -o shared_resouce_mutex shared_resource_mutex.c -lpthread
Execute: ./shared_resource_mutex
*/
#include
#include
#define iterations 300000000
long long shared_resource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// Thread function to modify shared resource
void* inc_dec_resource(void* arg){
//get the pointer from main thread and dereference it to put the value in resource_value
int resource_value = *(int *) arg;
for(int i=0; i < iterations; i++){
shared_resource += resource_value;
}
pthread_exit(NULL);
}
int main(void){
// Thread 1 to increment shared resource
pthread_t tid1, tid2;
int value1 = 1;
pthread_create(&tid1, NULL, inc_dec_resource, &value1);
// Thread 2 to increment shared resource
int value2 = -1;
pthread_create(&tid2, NULL, inc_dec_resource, &value2);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Shared resource value: %lld ", shared_resource);
return 0;
}
Requirement:
- Compile and run the above program. Execute it 5 times in the command prompt. What do you see in the result?
- Try executing the command with $ time ./shared_resource_mutex. What do you see other than printf statement? Copy and paste and report how long did the threads take to run.
- Try switching the joins
pthread_join(tid2, NULL);
pthread_join(tid1, NULL);
Do you see any difference? Please report if and why you do or do not see any difference in terms of the randomness in the result of the shared resource.
- In the inc_dec_resource() function, implement mutual exclusion (pthread_mutex_lock) to ensure that the result becomes 0 every time when you execute your program. Put your updated code in the report (highlighted) and show your screenshot of the execution by running the script three time using $ time ./shared_resource_mutex. Hint: Your loop is incrementing/decrementing the resource which should be protected by each thread while it is executing that portion.
can someone help me please using linux?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
