这个并行流可以工作吗?

发布于 2024-12-29 12:55:50 字数 864 浏览 6 评论 0原文

我正在尝试将并行处理组件添加到单线程单进程程序中。我刚刚学习一些多重处理方法,因此并不完全确定它们的功能。

我希望实现的程序逻辑:

  • 主进程调用函数。
    • 在 for 循环开始时调用函数 fork()。
      • 子级继续执行功能工作,执行其他子功能或根据时间检查退出。
    • 同时,父进程首先结束 for 循环并再次开始,从而重新分叉第二个子进程。
  • 函数将继续执行,直到执行了大约 10 个 fork() 后 for 循环结束。
  • 一旦完成,函数就会根据更高级别的计时器再次调用。

这个实施会起作用吗?示例代码:

check_timer() {
   for(i = 0; i < 10; i++) {
      pid_t pid = fork();
      if(pid == 0) {
         execute child 1 checks and possible executes..
         exit(); // when completed
      }
      else {
         parent maybe does something or just ends first round of for loop..
      }
   }
some implementation of wait(); to wait for all children to finish before leaving check_timer() function..
}

这是否会同时创建最多 10 个子进程,并在父进程的后台执行,然后等待子进程完成?另外,一些有关如何使用 wait() 的提示也会有所帮助。

I am trying to add a parallel processing component to a single thread single process program. I am just learning some of the multi-processing methods and as such am not totally sure of their capabilities.

The program logic I am looking to implement:

  • main process calls a function.
    • called function fork()'s at start of a for loop.
      • child continues with function work either performing other sub-functions or exiting back based on time checks.
    • meanwhile, parent ends first for loop round and starts again thus re-forking a second child.
  • function continues until for loop finishes after around 10 fork()'s have been executed.
  • function gets called again once completed based on a higher level timer.

Will this implementation work? Example code:

check_timer() {
   for(i = 0; i < 10; i++) {
      pid_t pid = fork();
      if(pid == 0) {
         execute child 1 checks and possible executes..
         exit(); // when completed
      }
      else {
         parent maybe does something or just ends first round of for loop..
      }
   }
some implementation of wait(); to wait for all children to finish before leaving check_timer() function..
}

Will this create up to 10 child processes at once executing in the background of a parent that then waits for the children to finish? Also some tips on how to use wait() would be helpful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

季末如歌 2025-01-05 12:55:50

是的,您最终将总共有 11 个进程。

您可能需要调用 waitpid 函数,直到不再有子进程(返回 ECHILD)。

编辑:刚刚注意到你需要 pid_t pid = fork();,而不是 pid = pid();

Yes, you will end up with 11 processes in total.

You likely want the waitpid function, called until there are no more children (a return of ECHILD).

EDIT: just noticed you need pid_t pid = fork();, not pid = pid();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文