Reputation: 1428
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);
children--;
}
children++;
id = fork();
}
}
}
Upvotes: 3
Views: 778
Reputation: 736
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.
Upvotes: 1
Reputation: 3185
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?
Upvotes: 3
Reputation: 328724
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.
Upvotes: 1
Reputation: 15134
You are right, wait
waits non-busy by handing over the CPU to the kernel until the child has exited.
Upvotes: 1