2012-11-10 19 views
0

如果我有以下代碼(來自Silberschatz,Operating Systems),爲什麼P行中的value = 0?我認爲父母的過程等待,直到孩子完成,孩子設置值= 5.fork()和wait()/由父母/子女更改的值

有人可以解釋這一點給我嗎?

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); 
} 

回答

3

當你叉,你創建一個一個全新的過程中,複製從父內存。 (操作系統可能會使用技巧來實現這一點,但語義依然存在。)

父級未看到對子級變量所做的更改 - 它們是具有單獨內存的獨立進程。

另一方面,線程共享相同的內存區域。因此,運行runner的線程中的更改對孩子的主線程是可見的。

+0

我明白了。非常感謝你! – soet