By default, all child processes have access to the parent´s variables.However, if multiple processes independently use the same variable,races can occur. To avoid races within fork/join blocks, shadow variables should be used.
EXAMPLE : without shadow variable
program main {
call();
delay(40);
printf(" END OF SIMUALTION \n");
}
task call(){
integer i;
delay(10);
for(i = 0; i < 3; i++) {
fork
{
delay(10);
printf(" time = %0d: i is %0d \n",get_time(LO),i);
}
join none
}
}
RESULTS
time = 20: i is 3 time = 20: i is 3 time = 20: i is 3 END OF SIMUALTION
Look at the solution, i is 3 in all the threads.
EXAMPLE :with shadow variable
program main {
call();
delay(40);
printf(" END OF SIMUALTION \n");
}
task call(){
shadowinteger i; // using shadow variable
delay(10);
for(i = 0; i < 3; i++) {
fork
{
delay(10);
printf(" time = %0d: i is %0d \n",get_time(LO),i);
}
join none
}
}
RESULTS
time = 20: i is 0 time = 20: i is 1 time = 20: i is 2 END OF SIMUALTION
The solution shows that ,Using the shadow keyword forces the Vera compiler to create a copy of the variable i local to each child process, which eliminates race conditions. Any descendants of the child processes will also have a copy of the variable local to that descendant.