The std::condition_variable is a synchronization primitive used to block a thread until notified by some other thread. The std::condition_variable::notify_one() member function is used to notify one waiting thread that there is a change to the condition variable.
Here are some examples of using the std::condition_variable::notify_one() function:
Example 1:
```c++ #include #include #include #include
std::mutex mtx; std::condition_variable cv; bool flag = false;
int main() { std::thread t(worker); std::this_thread::sleep_for(std::chrono::seconds(1)); // simulate work flag = true; cv.notify_one(); t.join(); return 0; }
This example shows a worker thread waiting for a flag to be set before continuing. The main thread sets the flag and notifies the worker thread using the std::condition_variable::notify_one() function.
Example 2:
c++
#include
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
std::vector vec;
void worker() {
std::unique_lock lock(mtx);
cv.wait(lock, []{ return !vec.empty(); });
std::cout << "Worker thread received data: ";
for(auto& i : vec) {
std::cout << i << " ";
}
std::cout << "\n";
}
int main() {
std::thread t(worker);
std::this_thread::sleep_for(std::chrono::seconds(1)); // simulate work
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
cv.notify_one();
t.join();
return 0;
}
```
This example shows a worker thread waiting for data to be added to a vector before continuing. The main thread adds data to the vector and notifies the worker thread using the std::condition_variable::notify_one() function.
These examples use the C++ STL (Standard Template Library) package.
C++ (Cpp) condition_variable::notify_one - 30 examples found. These are the top rated real world C++ (Cpp) examples of std::condition_variable::notify_one extracted from open source projects. You can rate examples to help us improve the quality of examples.