并行进程不共享相同的数据

时间:2018-01-27 06:25:11

标签: c parallel-processing fork system-calls

我编写了一个小C代码,它存在一个变量作为int指针。进程应该做的是减去该变量的值,直到它达到0。 问题是,即使程序打印的地址相同,每个进程似乎都有自己的变量副本。是否会发生这种情况,因为每个进程在内存中都有自己的空间?

这是输出:

START
Account address: 0x7ffee5820be0
Parent substracted 10. Account value: 90, address 0x7ffee5820be0
Parent substracted 10. Account value: 80, address 0x7ffee5820be0
Parent substracted 10. Account value: 70, address 0x7ffee5820be0
Parent substracted 10. Account value: 60, address 0x7ffee5820be0
Parent substracted 10. Account value: 50, address 0x7ffee5820be0
Parent substracted 10. Account value: 40, address 0x7ffee5820be0
Parent substracted 10. Account value: 30, address 0x7ffee5820be0
Parent substracted 10. Account value: 20, address 0x7ffee5820be0
Parent substracted 10. Account value: 10, address 0x7ffee5820be0
Parent substracted 10. Account value: 0, address 0x7ffee5820be0
Child substracted 10. Account value: 90 , address 0x7ffee5820be0
Child substracted 10. Account value: 80 , address 0x7ffee5820be0
Child substracted 10. Account value: 70 , address 0x7ffee5820be0
Child substracted 10. Account value: 60 , address 0x7ffee5820be0
Child substracted 10. Account value: 50 , address 0x7ffee5820be0
Child substracted 10. Account value: 40 , address 0x7ffee5820be0
Child substracted 10. Account value: 30 , address 0x7ffee5820be0
Child substracted 10. Account value: 20 , address 0x7ffee5820be0
Child substracted 10. Account value: 10 , address 0x7ffee5820be0
Child substracted 10. Account value: 0 , address 0x7ffee5820be0

2 个答案:

答案 0 :(得分:6)

是的,你的假设是正确的。

如果您想共享内存空间,可以选择以下几种方法:

  • 要么查看共享内存 - " POSIX共享内存" " System V共享内存" ,或
  • 使用线程 - C11 / C ++ 11线程或" pthreads" (即POSIX线程) - 自动共享相同的内存空间,或
  • 使用 Redis ,这是一个非常快速的内存数据结构服务器(队列,列表,集合,哈希,字符串/整数/浮点数)然后你可以共享变量(实际上是原子的)世界各地的进程之间。

答案 1 :(得分:1)

查看这篇文章,我认为它将解释为什么父母和孩子的地址似乎相同,以及父母和孩子之间不共享整个记忆状态的事实:

fork() system call and memory space of the process