If I have the following code (from Silberschatz, Operating Systems), why becomes value = 0 in Line P? I thought the parent process waits until the child is finished, and the child sets value = 5.
Can someone explan this to me?
int value = 0;
void *runner(void *param);
int main(int argc, char *argv[])
{
int pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork();
if (pid == 0) {
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,NULL);
pthread_join(tid,NULL);
printf("CHILD: value= %d \n",value); /* LINE C */
}
else if (pid > 0) {
wait(NULL);
printf("PARENT: value= %d \n",value); /* LINE P */
}
}
void *runner(void *param) {
value = 5;
pthread_exit (0);
}
When you fork, you create a completely new process with a copy of the memory from the parent. (The OS might use tricks to make this fast, but the semantics remain.)
The parent doesn’t see the changes done to variables in the child – they’re separate processes with separate memory.
Threads, on the other hand, share the same memory area. So the change in the thread that ran
runneris visible to the child’s main thread.