Busy Waiting

Busy waiting literally means waiting while busy using the CPU.

When a thread tries to use a shared resource and another thread is already holding the lock, instead of sleeping, it goes through an infinite loop and continuously checks to see if the lock has been released.

Example Code

volatile int lock = 0;

void critical_section(){
    while (lock == 1) {
    }
    lock = 1;
    lock = 0;
}

It is implemented like this.

Why Use It?

There is a reason to use this as it wastes CPU by running an infinite loop without necessarily putting it to sleep.

  • Speed is fast: When the conditions are met, the speed is fast. A method such as a mutex sleeps when the lock is not obtained and wakes up when the lock is released. This method is heavy because it involves context switching, but this method allows the next code to be executed without delay as soon as the lock is released because the thread is continuously running.

However, the core that is looping continues to loop infinitely until the lock is released, and the occupancy rate is 100, which is wasted.

Especially in a single-core environment, there is a risk of deadlock.