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

本文详细介绍了C++中条件变量(condition_variable)的使用方法及注意事项,包括如何避免通知丢失等问题,并给出了具体的代码示例。
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


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值