user318747
user318747

Reputation: 1428

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);
                     children--;
                 }
                 children++;
                 id = fork();
             }
    }
}

Upvotes: 3

Views: 778

Answers (4)

verisimilidude
verisimilidude

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

user472875
user472875

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

Aaron Digulla
Aaron Digulla

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

Peter G.
Peter G.

Reputation: 15134

You are right, wait waits non-busy by handing over the CPU to the kernel until the child has exited.

Upvotes: 1

Related Questions