这个并行流可以工作吗?
我正在尝试将并行处理组件添加到单线程单进程程序中。我刚刚学习一些多重处理方法,因此并不完全确定它们的功能。
我希望实现的程序逻辑:
- 主进程调用函数。
- 在 for 循环开始时调用函数 fork()。
- 子级继续执行功能工作,执行其他子功能或根据时间检查退出。
- 同时,父进程首先结束 for 循环并再次开始,从而重新分叉第二个子进程。
- 在 for 循环开始时调用函数 fork()。
- 函数将继续执行,直到执行了大约 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.
- called function fork()'s at start of a for loop.
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您最终将总共有 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 ofECHILD
).EDIT: just noticed you need
pid_t pid = fork();
, notpid = pid();