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 threadc use two threads to run the function worker. Each thread runs function worker, and update the value of the global variable counter times. This program is run two different times, The first time the output is and the second time is weird A reasonable explanation for the phenomenon is:
#include
#include
#include "common.h
volatile int counter ;
nt loops;
void workervoid arg
int i;
for ; loops;
counter;
return NULL;
int mainint argc, char argv
if argc
fprintfstderr "usage: threads
;
exit;
loops atoiargv;
pthreadt p p;
printfInitial value : sd
counter;
Pthreadcreate&pl NULL, worker, NULL;
Pthreadcreatesp NULL, worker, NULL;
Pthreadjoinp NULL;
PthreadJoinp NULL;
printfFinal value : d
counter;
return ;
Output
promptthread
Initial value :
Final value : huh??
promptthread
Initial value :
Final value : 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
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
