目录
- 1 概述
- 2 使用实例
- 3 接口使用
- 3.1 wait
- 3.2 wait_for
- 3.3 wait_until
- 3.4 notify_one
- 3.5 notiry_all
- 3.5 notify_all_at_thread_exit
1 概述
条件变量是一个能够阻塞调用线程直到被通知恢复的对象。
当调用其中一个等待函数时,它使用unique_lock(通过互斥锁)来锁定线程。线程保持阻塞状态,直到被另一个调用同一condition_variable对象上的通知函数的线程唤醒。
条件变量类型的对象总是使用unique_lock来等待.
其类图如下:
2 使用实例
struct Function4NotiryAll
{bool is_ready = false;std::mutex mutex;std::condition_variable cv;int counter = 0;void print_id(int id){std::unique_lock<std::mutex> lock(mutex);while(!is_ready)cv.wait(lock);std::cerr << "id:" << id << std::endl;counter++;}void go(){std::unique_lock<std::mutex> lock(mutex);is_ready = true;cv.notify_all();}
};void ConditionVariableSuite::notiry_all()
{std::thread threads[10];Function4NotiryAll function;for(int i = 0; i < 10; ++i)threads[i] = std::thread(&Function4NotiryAll::print_id, std::ref(function), i);function.go();for(auto & thread : threads)thread.join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}
3 接口使用
3.1 wait
struct Function4Wait
{volatile int cargo = 0;int counter = 0;std::mutex mutex;std::condition_variable cv;inline bool have_cargo() { return cargo != 0; }inline void consume_cargo() { cargo = 0; }void consume(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);while(!have_cargo())cv.wait(lock);std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}void consume_with_predicate(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);cv.wait(lock, std::bind(&Function4Wait::have_cargo, this));std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}inline void product(int n){std::unique_lock<std::mutex> lock(mutex);cargo = n;cv.notify_one();}
};void ConditionVariableSuite::wait()
{Function4Wait function; std::thread thread[