I read a book that gives the next example:
int value=0
int thread_func(int id) {
int temp;
temp=value+id;
printf("Thread%d value: %d", id, temp);
value=temp;
}
int main() {
int fork_id, status, i;
pthread_t tids[3];
fork_id=fork();
if (fork_id == 0) {
for (i=1; i≤3; i++)
pthread_create(&tids[i-1], NULL, thread_func, i);
for (i=0; i≤2; i++)
pthread_join(tids+i, &status);
printf("Second process value: %d", value);
}
else {
wait(&status);
printf("First process value: %d", value)
}
I don’t understand two main things:
As I read, the only value that the line has in printf("First process value: %d", value) is 0.
But why? wait(&status) is wait until the child process is terminate. In out case, it will terminate only after all the joins would done. meaning, when the value is 6.
Second, in the line printf("Second process value: %d", value);, the vaule can be from 1 to 6. This is also strange, because we have the join instruction.
The answers to your questions:
The value will be 0 in the parent process because when the
forkoccurs the address space of the parent is duplicated (along with the variablevalue) in the child process. Hence, althoughvalueis changed in the child, this change is not reflected in the parent as they are different variables.Since there is no synchronization involved, there is no way to know in which order the variable
valueis changed by the three child threads. Specifically, each thread has a localtempvariable with a different value, which is then copied in the globalvaluevariable, but there is no way to know in which order the threads will overwritevaluewithtemphere:value = temp;. Hence, its value can vary between executions.