【问题标题】:fork() and wait() / values changed by parent/childfork() 和 wait() / 父/子改变的值
【发布时间】:2012-11-10 13:17:31
【问题描述】:

如果我有以下代码(来自 Silberschatz,操作系统),为什么 P 行中的 value = 0?我以为父进程等到子进程完成,子进程设置value = 5。

谁能给我解释一下?

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

【问题讨论】:

    标签: c fork process wait


    【解决方案1】:

    当你 fork 时,你创建了一个全新的进程,其中包含来自父进程的内存副本。 (操作系统可能会使用一些技巧来加快速度,但语义仍然存在。)

    父级看不到对子级变量所做的更改 - 它们是具有独立内存的独立进程。

    另一方面,线程共享相同的内存区域。所以运行runner的线程的变化对子主线程是可见的。

    【讨论】:

    • 我明白了。非常感谢!
    猜你喜欢
    • 2014-04-21
    • 2011-02-12
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多