Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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

Big Data Concepts, Theories, And Applications

Authors: Shui Yu, Song Guo

1st Edition

3319277634, 9783319277639

More Books

Students also viewed these Databases questions

Question

1. What causes musculoskeletal pain?

Answered: 1 week ago