c - C 中的全局变量不会跨线程更新

标签 c multithreading pthreads

我什至都不好意思问这个问题,因为我认为我的实验结果会非常明显。

我的目的是演示跨线程更新全局变量的潜在陷阱。我预计该值会增加(即使只增加 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

最佳答案

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

关于c - C 中的全局变量不会跨线程更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51350323/

相关文章:

c - 快速排序实现麻烦

java - 将数据传递给正在运行的线程的正确方法是什么

linux - 是否有可能知道当前线程获得了多少 CPU 使用率?

c++ - 如果在共享内存中,pthread 互斥锁是否可以跨线程工作?

multithreading - 知道有多少人在等待 pthread 互斥锁

c - 在C中使用函数指针有效吗?

c++ - 如何将一个整数与另外两个整数分开? C/C++

c - 将整数类型转换为 void*

c - 为什么 char*p[10] 被编译器认为是 char** p?

java - Java 编译器是否可以重新排序同步语句以进行优化?