这是我的代码:
#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/