什么是std :: unique_lock的工作与std :: conditional_variable :: wait() [英] what's the job of std::unique_lock when used with std::conditional_variable::wait()

查看:555
本文介绍了什么是std :: unique_lock的工作与std :: conditional_variable :: wait()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们等待一个 std :: conditional_variable 时,我需要一个 std :: unique_lock 。所以我看看在VS 2013的图书馆代码,并得到更多的困惑。这是 std :: conditional_variable :: wait()如何实现的:

I'm quite confused with the need of a std::unique_lock when wait a std::conditional_variable. So I look into the library code in VS 2013 and get more confused. This is how std::conditional_variable::wait() implemented:

void wait(unique_lock<mutex>& _Lck)
    {   // wait for signal
    _Cnd_waitX(&_Cnd, &_Lck.mutex()->_Mtx);
    }

这是一个笑话吗?将互斥体包裹在unique_lock中,什么都不做,但后面得到它?为什么不在参数列表中使用互斥?

Is this some kind of joke? Wrap a mutex in a unique_lock and do nothing but get it back latter? Why not just use mutex in the parameter list?

推荐答案

/ code>,你想要在一些变量的值改变时发出信号(因此 condition_variable )。现在,由于你从多个线程访问有问题的变量(否则你不需要同步),它可能会被互斥锁保护。所以,当你等待变量的变化,你必须放弃互斥,当你得到的信号,你必须重新获得它。这是这个功能为你做的。

The idea is that when you call wait, you want to be signaled when the value of some variable changes (hence condition_variable). Now, since you are accessing the variable in question from multiple threads (otherwise you wouldn't need synchronization), it will probably be protected by a mutex. So, while you wait for the variable to change, you have to relinquish the mutex, and when you get the signal, you have to reaquire it. This is what this function does for you.

这篇关于什么是std :: unique_lock的工作与std :: conditional_variable :: wait()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆