Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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

SQL Database Programming

Authors: Chris Fehily

1st Edition

1937842312, 978-1937842314

More Books

Students also viewed these Databases questions