GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||
GeezerVison is showing www.tutorialspoint.com — C++ Library - <condition_variable>
Selected Reading
C++ Library - <condition_variable>The <condition_variable> in C++ is a synchronization primitive that allows threads to wait for certain conditions to be met before proceeding. It is useful in multi-threading applications, where one or more threads need to coordinate their actions based on shared data. By using condition variables, we can manage concurrent tasks, ensuring that threads either wait or proceed depending on specific conditions. 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 <condition_variable> HeaderTo include the <condition_variable> header in your C++ program, you can use the following syntax. #include <condition_variable> Functions of <condition_variable> HeaderBelow is list of all functions from <condition_variable> header.
Thread WaitingIn the following example, we are going to show how a thread can wait for a condition to be true. #include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
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;
}
OutputFollowing is the output of the above code − Waiting For Signal... Signal Received Advertisements
| ||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |