condition_variable

condition_variable

#include <condition_variable>

官方链接:http://www.cplusplus.com/reference/condition_variable/condition_variable/

(condition variable )条件变量是一个能够阻塞调用线程直到被通知恢复的对象。

当调用其等待函数之一时,它使用 unique_lock(通过互斥锁)来锁定线程。 该线程保持阻塞状态,直到被另一个线程唤醒,该线程在同一个 condition_variable 对象上调用通知函数。

condition_variable 类型的对象总是使用 unique_lock< mutex> 来等待:对于适用于任何类型的可锁定类型的替代方案,请参阅 condition_variable_any

Member functions
(constructor) Construct condition_variable (public member function )
(destructor) Destroy condition_variable (public member function )
Wait functions
wait Wait until notified (public member function )
wait_for Wait for timeout or until notified (public member function )
wait_until Wait until notified or time point (public member function )
Notify functions
notify_one Notify one (public member function )
notify_all Notify all (public member function )

example

// condition_variable example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\n';
}

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  ready = true;
  cv.notify_all();
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_id,i);

  std::cout << "10 threads ready to race...\n";
  go();                       // go!

  for (auto& th : threads) th.join();

  return 0;
}

Possible output (thread order may vary):


10 threads ready to race...
thread 2
thread 0
thread 9
thread 4
thread 6
thread 8
thread 7
thread 5
thread 3
thread 1
文章目录