Question: Modify the below code by introducing pthread mutex variables, so that accesses to the shared variable are properly synchronized. he synchronized version must work with

Modify the below code by introducing pthread mutex variables, so that accesses to the shared variable are properly synchronized. he synchronized version must work with the COMMAND LINE parameter set to 1, 2, 3, 4, and 5 etc.

Accesses to the shared variables are properly synchronized if:

(i) each iteration of the loop in SimpleThread() increments the variable by exactly one and (ii) each thread sees the same final value.

It is necessary to use a pthread barrier [2] in order to allow all threads to wait for the last to exit the loop.

__________________________________________________________________________

//Code to edit:

#include #include #include #include #include #include #include #include #include #include

int SharedVariable = 0; void *SimpleThread(void *i) {

int *p; p = i; int num, val = 0; for(num = 0; num < 20; num++) { if (random() > RAND_MAX / 2) usleep(10); val = SharedVariable; //printf("------------------------ "); printf("*** thread %d sees value %d ", *p, val); SharedVariable = val + 1; } val = SharedVariable; printf("Thread %d sees final value %d ", *p, val); }

int main(int argc, char *argv[]) { pthread_t *tid; int i; if (argc != 2){ printf("Invalid number of arguments "); printf("Usage a.out "); return 0; } else { int valid = 1; for (i = 0; i if (argv[1][i] < '0' || argv[1][i] > '9'){ valid = 0; break; } }

if (valid == 0){ printf(" Please provide a positive integer as an argument "); } else { int n = atoi(argv[1]); tid = (pthread_t *)malloc(sizeof(pthread_t) * atoi(argv[1])); int *j = (int *)malloc(sizeof(int)*n); for (i = 0; i j[i] = i; for (i = 0; i pthread_create(&tid[i], NULL, SimpleThread, &j[i]); } for (i = 0; i pthread_join(tid[i], NULL); } } } exit(0); }

__________________________________________________________________________

An example provided for the first function is as follows:

E.g.,for

(num = 0; num < 20; num++) { #ifdef PTHREAD _SYNC /* put your synchronization-related code here */ #endifval = SharedVariable; printf("*** thread %d sees value %d ", which, val); SharedVariable = val + 1; ....... }

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 Databases Questions!