c++wait

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


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?


Solution

  • 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.