
- C++ Library - Home
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- The C++ STL Library
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- The C++ Advanced Library
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ Library -
- C++ STL Library Cheat Sheet
- C++ STL - Cheat Sheet
- C++ Programming Resources
- C++ Programming Tutorial
- C++ Useful Resources
- C++ Discussion
C++ Library -
The
It is used in conjunction with std::mutex and is generally used with std::unique_lock. The unique_lock is passed to the condition_variable to release the lock when the thread is waiting, allowing the other threads to modify the shared data.
Including Header
To include the
#include
Functions of Header
Below is list of all functions from
Sr.No. | Functions & Description |
---|---|
1 |
notify_one
It notifies one waiting thread. |
2 |
notify_all
It notifies all waiting threads. |
3 |
wait
It blocks the current thread until the condition variable is awakened. |
4 |
wait_for
It blocks the current thread until the condition variable is awakened or after the specified timeout duration. |
Thread Waiting
In the following example, we are going to show how a thread can wait for a condition to be true.
#include#include #include #include std::mutex a; std::condition_variable b; bool ready = false; void x() { std::unique_lock < std::mutex > lock(a); std::cout << "Waiting For Signal..." << std::endl; b.wait(lock, [] { return ready; }); std::cout << "Signal Received" << std::endl; } int main() { std::thread y(x); std::this_thread::sleep_for(std::chrono::seconds(3)); { std::lock_guard < std::mutex > lock(a); ready = true; } b.notify_one(); y.join(); return 0; }
Output
Following is the output of the above code −
Waiting For Signal... Signal Received