【问题标题】:Multiple fork() Concurrency多个 fork() 并发
【发布时间】:2010-11-25 17:59:22
【问题描述】:

你如何使用 fork() 命令来生成 10 个进程并让它们同时执行一项小任务。

并发是一个有效的词,许多展示如何使用 fork 的地方在他们的演示中只使用一次 fork() 调用。我以为你会使用某种 for 循环,但我试过了,在我的测试中似乎 fork() 正在产生一个新进程,开始工作,然后产生一个新进程。所以它们似乎是按顺序运行的,但是如果有意义的话,我怎么能同时分叉并让 10 个进程同时完成工作呢?

谢谢。

更新:感谢大家的回答,我想我最初只是误解了 fork() 的某些方面,但现在我明白了。干杯。

【问题讨论】:

  • 顺便说一句——你真的想要进程(如你的文本)或线程(如你的标签)。如果处理你想要的标签是 [multiprocessing]

标签: c unix command-line concurrency multiprocessing


【解决方案1】:

循环调用fork()

添加代码以等待每个 cmets 的孩子:

int numberOfChildren = 10;
pid_t *childPids = NULL;
pid_t p;

/* Allocate array of child PIDs: error handling omitted for brevity */
childPids = malloc(numberOfChildren * sizeof(pid_t));

/* Start up children */
for (int ii = 0; ii < numberOfChildren; ++ii) {
   if ((p = fork()) == 0) {
      // Child process: do your work here
      exit(0);
   }
   else {
      childPids[ii] = p;
   }
}

/* Wait for children to exit */
int stillWaiting;
do {
   stillWaiting = 0;
    for (int ii = 0; ii < numberOfChildren; ++ii) {
       if (childPids[ii] > 0) {
          if (waitpid(childPids[ii], NULL, WNOHANG) != 0) {
             /* Child is done */
             childPids[ii] = 0;
          }
          else {
             /* Still waiting on this child */
             stillWaiting = 1;
          }
       }
       /* Give up timeslice and prevent hard loop: this may not work on all flavors of Unix */
       sleep(0);
    }
} while (stillWaiting);

/* Cleanup */
free(childPids);

【讨论】:

  • 哦,绝对是。否则,您将邀请有限的叉子炸弹。
  • 小心僵尸群。您需要在父进程中等待(2)这些进程。
  • 我运行了这段代码,但它有一些问题,进程永远不会完成并且永远等待......
  • 子进程在做什么?
  • 如果 childPids[ii] 没有完成,Waitpid 返回 0 和 WNOHANG;它返回 childPids[ii] 否则。事实上,值为 0 时,循环永远不会结束。
【解决方案2】:

当您分叉进程时,将同时运行。但请注意,除非您有足够的可用空闲处理器,否则它们实际上可能不会同时执行,这并不重要...

您的第二段似乎您不了解 fork 的工作原理,您必须检查返回码以查看您是在父进程中还是在分叉进程中。因此,您可以让父进程运行一个循环来分叉 10 个进程,然后在子进程中同时执行您想做的任何事情。

【讨论】:

    【解决方案3】:

    只需在“主”进程中循环,一个接一个地生成一个子进程,每个子进程分配一个特定的任务。

    【讨论】:

      【解决方案4】:

      您可能还想研究 POSIX 线程(或 pthreads)。这是一个教程:

      https://computing.llnl.gov/tutorials/pthreads/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        • 2010-12-12
        • 2017-09-05
        • 1970-01-01
        相关资源
        最近更新 更多