c - 多线程编程中关于全局变量的一些问题

标签 c multithreading global-variables

这是我的代码:

#include <stdio.h>
#include <unistd.h>

static volatile int t=0;

int main(void){
    int i;
    for (i=0; i<2; i++){
        fork();
        printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
    }
    printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
    return 0;
}

这样的输出:

pid:16232: addr:134518684 val:0
pid:16233: addr:134518684 val:0
pid:16232: addr:134518684 val:1
pid:16232: addr:134518684 val:2
pid:16234: addr:134518684 val:1
pid:16234: addr:134518684 val:2
pid:16233: addr:134518684 val:1
pid:16233: addr:134518684 val:2
pid:16235: addr:134518684 val:1
pid:16235: addr:134518684 val:2

全局变量t的地址相同,所有线程操作的是同一个变量t吗?我预计 val 是“0, 1, 2, 3, 4, 5, ...”,我该怎么办?

最佳答案

这是 fork 一个不同的进程,不是生成新线程。结果是有道理的,因为 fork 进程将获得父进程内存的副本

如果您打算使用 fork ,这是一种更标准的方法:

int main ()
{
   int pid;

   pid = fork();

   if (pid == 0) {
      // This will be where the child process executes
   } else if (pid > 0) {
     // This is where the parent process executes
   }
   return 0;
}

关于c - 多线程编程中关于全局变量的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12403895/

相关文章:

variables - 如何从脚本/命令行设置全局变量?

python - 在 Python 的双重嵌套函数中访问变量

multithreading - WSA发送到多线程iocp服务器中的所有已连接套接字

java - 了解多线程

c - 当计算机的本质是状态机时,为什么要发明阻塞调用?

c - 为什么#if 0 与#if (1 > 1)?

c# - 如何避免此异步/等待程序中可能的堆栈溢出?

singleton - 为什么要使用 Application 子类来保存全局变量?

c - 在外部写入时从 C 中读取文件

c - 不使用字符数组打印输入