c中线程的内存访问
memory access of threads in c
我有点难以理解以下 c 程序的输出
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int i = 1;
pid_t childId = fork();
pid_t pid = getpid();
if (childId == -1) {
perror("fork() failed");
} else if (childId == 0) {
printf("child PID: %d\n", pid);
int *j = NULL;
j = &i;
(*j)++;
printf("value i in child: %d\t@adresse: %p\n",i ,&i);
} else {
pid_t pid = getpid();
printf("parent PID: %d\nwait for child\n", pid);
waitpid(childId, NULL, 0);
printf("value i in parent: %d\t@adresse: %p\n",i ,&i);
}
return 0;
}
输出:
parent PID: 10656
wait for child
child PID: 10657
value i in child: 2 @address: 0x7fff93b720c0
value i in parent: 1 @address: 0x7fff93b720c0
子线程递增'i',存储在给定地址。等待子线程后,父线程继续执行并在相同地址但使用初始值打印 'i' 。这不也应该是2吗?
用户应用程序使用 virtual memory。如果您使用 fork()
,您将创建一个单独的进程,该进程使用与父进程具有相同地址的虚拟内存。
因此两个进程都使用具有相同地址的虚拟地址 space(如您的 printfs 所示),但它们可能在不同的物理内存上运行。
来自 Wikipedia 的更详细解释(强调我的):
The fork operation creates a separate address space for the child. The
child process has an exact copy of all the memory segments of the
parent process. In modern UNIX variants that follow the virtual memory
model from SunOS-4.0, copy-on-write semantics are implemented and the
physical memory need not be actually copied. Instead, virtual memory
pages in both processes may refer to the same pages of physical memory
until one of them writes to such a page: then it is copied.
我有点难以理解以下 c 程序的输出
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int i = 1;
pid_t childId = fork();
pid_t pid = getpid();
if (childId == -1) {
perror("fork() failed");
} else if (childId == 0) {
printf("child PID: %d\n", pid);
int *j = NULL;
j = &i;
(*j)++;
printf("value i in child: %d\t@adresse: %p\n",i ,&i);
} else {
pid_t pid = getpid();
printf("parent PID: %d\nwait for child\n", pid);
waitpid(childId, NULL, 0);
printf("value i in parent: %d\t@adresse: %p\n",i ,&i);
}
return 0;
}
输出:
parent PID: 10656
wait for child
child PID: 10657
value i in child: 2 @address: 0x7fff93b720c0
value i in parent: 1 @address: 0x7fff93b720c0
子线程递增'i',存储在给定地址。等待子线程后,父线程继续执行并在相同地址但使用初始值打印 'i' 。这不也应该是2吗?
用户应用程序使用 virtual memory。如果您使用 fork()
,您将创建一个单独的进程,该进程使用与父进程具有相同地址的虚拟内存。
因此两个进程都使用具有相同地址的虚拟地址 space(如您的 printfs 所示),但它们可能在不同的物理内存上运行。
来自 Wikipedia 的更详细解释(强调我的):
The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process. In modern UNIX variants that follow the virtual memory model from SunOS-4.0, copy-on-write semantics are implemented and the physical memory need not be actually copied. Instead, virtual memory pages in both processes may refer to the same pages of physical memory until one of them writes to such a page: then it is copied.