How does C++ allow to wait without excessive CPU usage

Viewed 1912

For example I have code

while (!something} {
    //waiting
}

it does wait for something, but it uses a lot of CPU. C++ have things like thread join, condition variable wait, mutex lock - which allow to wait, so it does check some condition, but it behaves like idle process - not consuming CPU time. How it is done and is there way to make while loop (or any other code) behave like this?

2 Answers

These are features necessarily backed by the operating system.

The OS is responsible for allocating time to your processes and threads, and you require these features to control (or, rather, make requests of) that mechanism.

Your C++ standard library implementation calls platform-specific functions provided by your operating system.

There is no way to replicate that yourself without using the kind of C++ types/functions you've already listed: mutexes & timers (or without calling those OS functions yourself, like we did in the olden days!). All you can do is a spin lock, like the one you already demonstrated.

You can achieve this by calling system calls that block the execution of the thread.

You don't usually call the system directly, but use a wrapper function instead, which is an abstraction over system specific details. This approach allows your program to be portable to different systems.

In fact, this is exactly what the standard functions such as std::condition_variable::wait are: an abstraction over system interface, which in this case blocks the thread. std::cin::operator>> is another example of function call that blocks the execution of the thread.

Related