Concurrency 4, condition_variable - C++11, 11 of n

来源:互联网 发布:淘宝关键词工具 编辑:程序博客网 时间:2024/06/06 08:40
1) condition_variable

Called without the predicate, both wait_for() and wait_until() return the following enumeration class values:

  • std::cv_status::timeout if the absolute timeout happened
  • std::cv_status::no_timeout if a notification happened

Called with a predicate as third argument, wait_for() and wait_until() return the result of the predicate (whether the condition holds).

2) Note:

  • Notifications are automatically synchronized so that concurrent calls of notify_one() and notify_all() cause no trouble.
  • All threads waiting for a condition variable have to use the same mutex, which has to be locked by a unique_lock when one of the wait() members is called. Otherwise, undefined behavior occurs.
  • Note that consumers of a condition variable always operate on mutexes that are usually locked. Only the waiting functions temporarily unlock the mutex performing the following three atomic steps (The problem with a naive approach like “lock, check state, unlock, wait” is that notifications arising between unlock and wait would get lost.):
  1. Unlocking the mutex and entering the waiting state
  2. Unblocking the wait
  3. Locking the mutex again
3) Example
#include <condition_variable>
#include <mutex>
#include <future>
#include <thread>
#include <iostream>
#include <queue>
std::queue<int> queue;

std::mutex queueMutex;
std::condition_variable queueCondVar;

void provider (int val)
{
    for (int i=0; i<6; ++i) {
        {
            std::lock_guard<std::mutex> lg(queueMutex);
            queue.push(val+i);
        } // release lock
        queueCondVar.notify_one();  // Note, without holding the mutex, which is good for C++11
        std::this_thread::sleep_for(std::chrono::milliseconds(val));
    }
}
void consumer (int num)
{
    while (true) {
        int val;
        {
            std::unique_lock<std::mutex> ul(queueMutex);
            queueCondVar.wait(ul,[]{ return !queue.empty(); });
            val = queue.front();
            queue.pop();
        } // release lock
        std::cout << "consumer " << num << ": " << val << std::endl;
    }
}
int main()
{
    auto p1 = std::async(std::launch::async,provider,100);
    auto p2 = std::async(std::launch::async,provider,300);
    auto p3 = std::async(std::launch::async,provider,500);

    auto c1 = std::async(std::launch::async,consumer,1);
    auto c2 = std::async(std::launch::async,consumer,2);

}

Footnote:
std::unique_lock<std::mutex> ul(queueMutex);
queueCondVar.wait(ul,[]{ return !queue.empty(); });  
"Equals"
std::unique_lock<std::mutex> ul(queueMutex);
while(queue.empty()) {
    queueCondVar.wait(ul);
}

4) condition_variable_any
It does not require using an object of class std::unique_lock as lock, so you can provide your own lock implementation but the class should implement lock and unlock member function