Reputation: 222
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?
Upvotes: 5
Views: 3119
Reputation: 1
Another way to wait without excessive CPU usage is using the while()
loop method to halt the whole code or maybe use getch()
from conio.h
to pause the program and continue when any key is pressed. I use this sometimes.
Upvotes: -2
Reputation: 238311
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.
Upvotes: 4
Reputation: 385108
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.
Upvotes: 3