原子内建函数可以跨多个进程使用吗?

Tom*_*n32 1 c fork atomic built-in-types

我将从.NET重新使用C,因此请原谅我的代码,但是我试图在现有的多进程程序中实现原子内置的增量器。

我写了一个测试程序,但无法正常工作。正确地将其增加到5,但是每个子级将值增加到6,而不是将其总和增加到10。监视器显示5。

我已经尝试过使用全局int进行各种更改,而不是将static int从main传递给子级,但是结果相同。任何帮助表示赞赏,谢谢。

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <sys/types.h>
  4 #include <stdlib.h>
  5 #include <unistd.h>
  6 #include "list.h"
  7 
  8 #define N 5
  9 static int globalcount = 0;
 10 
 11 void Monitor()
 12 {
 13     sleep(1);
 14     printf("Monitor Value %d\n", globalcount);
 15 }
 16 
 17 void Child()
 18 {   
 19     int value = __sync_add_and_fetch(&globalcount, 1);
 20     printf("Child Value %d\n", value);
 21 }
 22 
 23 int main(int argc, char** argv)
 24 {
 25     int i;
 26     int value;
 27     static int count = 0;
 28     pid_t pid[N];
 29     pid_t pidkey;
 30 
 31     for (i = 0; i < N; ++i) {
 32         value = __sync_add_and_fetch(&globalcount, 1);
 33         printf("Value %d\n", value);
 34     }
 35     printf("\n\n\n");
 36 
 37     if ((pidkey = fork()) == 0) {
 38         Monitor();
 39     } else if (pidkey > 0) {
 40         for (i = 0; i < N; i++)
 41         {
 42             if ((pid[i] = fork()) == 0) {
 43                 Child();
 44                 break;
 45             }
 46         }
 47     }
 48     return 0;
 49 }   
Run Code Online (Sandbox Code Playgroud)

Wil*_*ill 5

如果内存正确地为我服务,则当fork()您使用进程时,子进程将获得变量的副本,或者变量是写时复制的。也就是说,在尝试更改之前,您实质上是指相同的数据。您要完成的工作不仅仅需要static在代码顶部声明一个变量。您需要研究使用共享内存,以便可以跨进程空间共享变量。由于要花很长时间才能找到答案,而且实际上不是5行答案,因此我将不得不稍后再进行详细编辑。但是,如果您shm_get在手册页中查找该功能(以及其他shm_*功能),文档非常丰富。Web上也有许多教程:搜索“ POSIX IPC共享内存教程示例”,您将获得描述该方法的各种信息。