Is this busy waiting?
Is this loop busy waiting, I would think the wait call takes care of that. If it is, how can it be fixed to not busy wait?
id = fork();
for (i = 0; i < 20; i++)
{
switch (id)
{
case 0:
/* do stuff with child */
exit(0);
default:
{
if (children>=3) {
int s;
wait(&s);
开发者_如何学JAVA children--;
}
children++;
id = fork();
}
}
}
wait
will cause the kernel to select other jobs that are not marked as blocked, so this isn't a case of busy-waiting. Also isn't switch a bit excessive for a fork(), why not use a simple if statement?
You are right, wait
waits non-busy by handing over the CPU to the kernel until the child has exited.
It's not really buys waiting (it doesn't check the status of the children in a loop; instead if blocks inside the wait()
call).
Nonetheless, the code can hog the CPU depending on what happens in do stuff with child
. That will look like busy waiting (CPU usage 100%) even though it's really several processes doing actual work.
I agree with you, waiting on the death of a child (even inside a loop) would not be busy waiting. OTOH you can get in real trouble if one or more of the child processes are compute intensive. The compute-intensive children will always be ready to run and it is not guaranteed that the parent will get the CPU.
精彩评论