Question: what are the shared variables in the program below ( note: A variable x is shared if and only if multiple threads reference some instance

what are the shared variables in the program below (note: A variable x is shared if and only if multiple threads reference some instance of x.) and what is the output of the program when the number of threads is 8 and number of elements per thread is 1? what about the case when number of threads is 1 and the number of elements per thread is 8? comment on the relative performance of these two cases:
#include "csapp.h"
#define MAXTHREADS 32
void *sum_mutex(void *vargp);
long gsum =0; // Global variable automatically initialized to 0
long nelems_per_thread;
sem_t mutex;
int main(int argc, char *argv[]){
long i, nelems, log_nelems, nthreads, myid[MAXTHREADS];
pthread_t tid[MAXTHREADS];
// Get input arguments
if (argc !=3){
printf("Usage: %s
", argv[0]);
exit(0);
}
nthreads = atoi(argv[1]);
log_nelems = atol(argv[2]);
nelems =(1L << log_nelems);
// Check input arguments
if ((nelems % nthreads)!=0|| log_nelems >31){
printf("Error: invalid nelems
");
exit(0);
}
// Begin psumutex
nelems_per_thread = nelems / nthreads;
sem_init(&mutex, 0,1);
// Create peer threads and wait for them to finish
for (i =0; i < nthreads; i++){
myid[i]= i;
pthread_create(&tid[i], NULL, sum_mutex, &myid[i]);
}
for (i =0; i < nthreads; i++){
pthread_join(tid[i], NULL);
}
// Print final answer
printf("result=%ld
", gsum);
exit(0);
}
void *sum_mutex(void *vargp){
long myid =*((long *)vargp);
long start = myid * nelems_per_thread;
long end = start + nelems_per_thread;
long i;
for (i = start; i < end; i++){
P(&mutex);
gsum += i;
V(&mutex);
}
return NULL;
}

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!