C++ condition_variable::wait_for() Function



The std::condition_variable::wait_for() function in C++, is a synchronization mechanism that blocks a thread until a specified duration has passed or a condition is met. It is works with the std::unique_lock on a mutex, ensuring the thread-safe operations.

This function returns the cv_status::timeout if the duration expires without the condition being satisfied or cv_status::no_timeout if the condition is met.

Syntax

Following is the syntax for std::condition_variable::wait_for() function.

cv_status wait_for (unique_lock<mutex>& lck, const chrono::duration<Rep,Period>& rel_time);
or
bool wait_for (unique_lock<mutex>& lck, const chrono::duration<Rep,Period>& rel_time, Predicate pred);

Parameters

  • lck − It indicates a unique_lock object whose mutex object is currently locked by this thread.
  • rel_time − It indicates the max time span during which the thread will block waiting to be notified.
  • pred − It indicates a callable object or function that takes no arguments and returns a value that can be evaluated as a bool.

Return value

This function returns pred(), regardless of whether the timeout was triggered.

Example 1

Let's look at the following example, where the main thread waits and displays updates until the 'c' reaches to zero.

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::mutex a;
std::condition_variable b;
int c = 4;
void x() {
   while (c > 0) {
      std::this_thread::sleep_for(std::chrono::seconds(1));
      std::lock_guard < std::mutex > lock(a);
      c--;
      b.notify_one();
   }
}
int main() {
   std::thread t(x);
   std::unique_lock < std::mutex > lock(a);
   while (!b.wait_for(lock, std::chrono::seconds(1), [] {
         return c == 0;
      })) {
      std::cout << "Countdown: " << c << "\n";
   }
   std::cout << "Countdown Finished.\n";
   t.join();
   return 0;
}

Output

Output of the above code is as follows −

Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Countdown Finished.
cpp_condition_variable.htm
Advertisements