While preparing for an exam, I've had this piece of code:
int y;
int main()
{
pid_t id;
int i,j;
y=0;
id=fork();
if(id==0){
for(i=0;i<5;i++){
y=y+2;
}
}else{
for(j=0;j<10;j++){
y=y+3;
}
}
wait(NULL);
}
Assume that y is in shared memory.
I need to find the minimum possible value of y.
I know the answer is 10, but I can't figure out why.
Since the parent process and the child process both have to add value to y, it doesn't matter in which order they'll run, the result stays the same which is 40.
The only way for y to be 10 is only if the parent process will die before entering the for loop.
I would love for some explanation why the minimum value of y could be 10.
Thanks in advance!
edit: The code doesn't have any evidence of y being in a shared memory but I have to assume that for understanding purposes