Question: The following program ( thread . c ) use two threads to run the function worker. Each thread runs function worker, and update the value

The following program (thread.c) use two threads to run the function worker. Each thread runs function worker, and update the value of the global variable counter 100000 times. This program is run two different times, The first time the output is 143012, and the second time is 137298(weird). A reasonable explanation for the phenomenon is:
```
#include
#include
#include "common.h"
volatile int counter =0;
1nt loops;
void *worker(void *arg){
int i;
for (1=0; 1 loops; 1++){
counter++;
}
return NULL;
}
int main(int argc, char *argv[]){
if (argc !=2){
fprintf(stderr, "usage: threads
");
exit(1);
}
loops = atoi(argv[1]);
pthread_t p1, p2;
printf("Initial value : sd
", counter);
Pthread_create(&pl, NULL, worker, NULL);
Pthread_create(sp2, NULL, worker, NULL);
Pthread_join(p1, NULL);
Pthread_Join(p2, NULL);
printf("Final value : %d
", counter);
return 0;
}
```
Output
prompt>./thread 100000
Initial value : 0
Final value : 143012// huh??
prompt>./thread 100000
Initial value : 0
Final value : 137298// what the??
There is not thread synchronization, this allows to overwrite the global variable counter
The scheduler is switching process
None of the above
There are two process and when they update the value the overwrite
The following program ( thread . c ) use two

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!