全局变量不会在C中的线程更新[关闭]

问题描述 投票:-1回答:1

我甚至不好问这个问题因为我认为我的实验结果非常明显。

我打算演示跨线程更新全局变量的潜在缺陷。我预计价值会增加(即使只是1)。

但结果是它似乎根本没有更新,我错过了关于如何跨线程共享数据的内容?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int global = 0;

void child_code(int i)
{
  sleep(i);
  global++;
  printf("Child %d: global=%p/%d\n", i, &global, global);
}

int main()
{
    pid_t pid;
    int i, num_children;

    num_children = 10;

    for (i=0; i<num_children; i++) {
        pid = fork();
        if (pid == -1) exit(1);

        /* see if we're the parent or the child */
        if (pid == 0) {
            child_code(i);
            exit(i);
        }
    }

    /* parent continues */
    for (i=0; i<num_children; i++) {
      pid = wait(NULL);
    }

    printf("Parent: global=%p/%d\n", &global, global);

    exit(0);
}

这是一个示例输出:

Child 1: global=0x10a5d7038/1
Child 2: global=0x10a5d7038/1
Child 3: global=0x10a5d7038/1
Child 4: global=0x10a5d7038/1
Child 5: global=0x10a5d7038/1
Child 6: global=0x10a5d7038/1
Child 7: global=0x10a5d7038/1
Child 8: global=0x10a5d7038/1
Child 9: global=0x10a5d7038/1
Parent: global=0x10a5d7038/0
c multithreading pthreads
1个回答
2
投票

fork()不创建线程,它创建具有单独内存段的单独进程。更准确地说,在Linux上,它克隆当前进程并将所有数据段页面标记为写时复制,这就是为什么一旦子进程尝试写入变量,它就会得到它自己的变量副本以及它自己的副本它所在的内存页面。

© www.soinside.com 2019 - 2024. All rights reserved.