Modify and run the program shown below in the following way. There is an array o
ID: 3840856 • Letter: M
Question
Modify and run the program shown below in the following way. There is an array of 20 elements defined in the program. The elements of the array are: [20 18 16 14 12 10 8 6 4 2 -10 -20 -30 -40 15 23 25 75 45 33]. Thread 1 adds the first five elements (i.e., 20, 18, 16, 14, 12), Thread 2 adds the next five elements (i.e., 10, 8, 6, 4, 2), Thread 4 adds the last five elements (23, 25, 75, 45, 33). Finally, the sum of all the 20 elements is printed by the program. include #include include #define NUM_THREADS 3 int counter=1; void *PrintHello(void *threadid) {counter = 2*counter+ (int) threadid; printf(" Thread Id: %d Counter: %d ", threadid, counter); pthread_exit(NULL);} int main(int arge, char *argv[]) {pthread_t threads[NUM_THREADS]; int rc, t; for(t=0;tExplanation / Answer
The modified code is as follows:
1. Include unistd.h (for using sleep function) as follows:
#include<unistd.h>
2.Add global array declaration and a global varaible integer N and modify NUM_THREADS as 4 as follows:
#define NUM_THREADS 4
int counter=1;
int array[20];
int N = 0;
3. PrintHello function will be modified as follows:
void *PrintHello(void *threadid)
{
counter = 2*counter+(int)threadid;
printf (" Thread Id:%d Counter: %d ",threadid,counter);
/*-------------------Modified Code-------------------*/
if (N == 0)){
for (int i = N; i<N + 5; i++){
array[i] = 20 - 2 * i;
}
N = 5; // Value is set so that the next thread can fill from N = 5 onwards
}
else {
if (N == 5)){
for (int i = N; i<N + 5; i++){
array[i] = 10 - 2 * (i - N);
}
N = 10; Value is set so that the next thread can fill from N = 10 onwards
}
else {
if (N == 10)){
for (int i = N; i<N + 4; i++){
array[i] = -10 - 10 * (i - N);
}
array[N+4] = 15;
N = 15; //Value is set so that the next thread can fill from N = 15 onwards
}
else {
if (N == 15)){
array[N] = 23;
array[N +1] = 25;
array[N + 2] - 75;
array[N + 3] - 45;
array[N + 3] - 33;
}
}
}
}
}
}
4. Main code is modified as follows:
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc,t;
int sum = 0;
/*-----------------Modified Cosde--------------------*/
for (t=0; t<NUM_THREADS; t++){
printf("Creating thread %d ",t);
rc = pthread_create(&threads[t],NULL,PrintHello, (void *)t);
if (rc) {
printf("ERROR:return code for pthread_create is %d ",rc);
exit(-1)
}
sleep(2); //This sleep is added so that the created thread gets enough time to fill the array.
}
printf(" Counter: %d ,counter);
for (int i = 0; i<20; i++)
sum = sum + array[i];
printf("Sum is %d ",sum);
pthread_exit(NULL)
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.