Multithreading – Performance Impact of Creating Threads That Loop Frequently

loopsmultithreadingperformance

This is a generic question that I've always wondered.

In general, is it intensive for a CPU to create threads that perform "while not true …" loops or similar?

For example, suppose I do:

// pseudo-code
new Thread(function() {
    while (!useHasDoneSomething) {
        // do nothing...
    }
    alert("you did something!");
}

So it's just a piece of code that runs in a thread that waits for something to happen.

For whatever reason I imagine that this would pressure the CPU. After all, even though it's just one little loop, it's re-running the loop the instant that a cycle is done. Wouldn't this mean that it's going through the cycle many times per millisecond? … Per nanosecond!?

The operating system will "handle" the program and the thread(s), right? But that's still an awful lot of attention to running a loop. If the CPU has nothing else to do, wouldn't it just focus on that loop, thereby consuming all the idle time?

What if I create 1000 threads that all do the same loop? How might that affect performance/CPU cycles?

Furthermore, is this how events function internally? When you're 'listening' for an event in Java, .NET, Javascript etc (such as a button press or a window resize), has a thread that loops been created?

Best Answer

In general, is it intensive for a CPU to create threads that perform "while not true ..." loops or similar?

Yes. Using such a loop is called busy waiting and it is called that for a reason. These busy loops check the condition as often and as fast as the processor can manage it, with the result that, if you stay in the loop long enough, the processor load goes reliably to 100%.

What if I create 1000 threads that all do the same loop? How might that affect performance/CPU cycles?

It only creates more work for the CPU doing noting.

Furthermore, is this how events function internally? When you're 'listening' for an event in Java, .NET, Javascript etc (such as a button press or a window resize), has a thread that loops been created?

No. Busy loops are a form of polling and a very inefficient one at that as well. Operating systems have other mechanisms to detect that an event has happened (e.g. an interrupt or a specific call) and they have mechanisms to let a thread wait for it without consuming CPU time. These mechanisms will also be used to implement the event mechanisms of languages like Java.