Question: [ Counting ] Consider the following program using pthread. #include #include #include #include common.h #include common _ threads.h int max; volatile int counter

[Counting] Consider the following program using pthread.
#include
#include
#include
#include "common.h"
#include "common_threads.h"
int max;
volatile int counter =0; // shared global variable
void mythread(void arg){
char *letter = arg;
int i; // stack (private per thread)
printf("%s: begin [addr of i: %p]
", letter, &i); //Line 1
for (i =0; i < max; i++){
counter = counter +1; // shared: only one
}
printf("%s: done
", letter);
return NULL;
}
int main(int argc, char *argv[]){
if (argc !=2){
fprintf(stderr, "usage: main-first loopcount
");
exit(1);
}
max = atoi(argv[1]);
pthread_t p1, p2;
printf("main: begin [counter =%d]
", counter,
(unsigned int) &counter);
Pthread_create(&p1, NULL, mythread, "A");
Pthread_create(&p2, NULL, mythread, "B");
// join waits for the threads to finish
Pthread_join(p1, NULL);
Pthread_join(p2, NULL);
printf("main: done
[counter: %d]
[should: %d]
",
counter, max*2); //Line 2
return 0;
}
1. Suppose in a run, we get the output. Corresponding to Line 1, we get the output from one
thread as follows:
A: begin [addr of i: 0x700004788f9c]
Can you infer the output from the other thread corresponding to Line 1? If, show
the output. If not, explain why.
2. This program takes the input from the command line for "max". In this run, we
have max as 1000000. What is the output corresponding to Line 2?
3. Does the above program have any problem? If no, explain your reasoning. If yes, show
your solution to fix that (you can copy and modify the code above with your changes briefly

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