[英]Why isn't std::condition_variable templated by lock type?
It's useful to have the ability to assert in debug mode, with reasonably small overhead, whether a mutex is locked. 能够以较小的开销在调试模式下声明互斥对象是否锁定是很有用的。 Viewing the known options, I've chosen to implement this using an
std::mutex
subclass due to the low overheads. 查看已知选项,由于开销低,我选择使用
std::mutex
子类来实现此目的 。
The interface of the subclass is a superset of that of std::mutex
, and so most things work well with it. 子类的接口是
std::mutex
的接口的超集,因此大多数事情都可以很好地使用它。 Eg, std::unique_lock
is templated to utilize any lock type that has a specific interface. 例如,
std::unique_lock
被模板化以利用具有特定接口的任何锁类型。
The problem is with std::condition_variable
, in particular the wait
members, eg: 问题出在
std::condition_variable
,特别是wait
成员,例如:
template<class Predicate>
void wait(std::unique_lock<std::mutex> &lock, Predicate pred);
As can be seen, the method requires a very specific unique_lock
/ mutex
combination. 可以看出,该方法需要一个非常特定的
unique_lock
/ mutex
组合。 Unfortunately, also, the Liskov principle doesn't extend for container<derived>
being converted into container<base>
. 不幸的是,同样,对于将
container<derived>
转换为container<base>
, Liskov原理也没有扩展。
I don't understand 我不明白
Even if the intent was to enforce the use of std::unique_lock
, then why couldn't the following be used: 即使目的是强制使用
std::unique_lock
,但为什么不能使用以下内容:
template<class Predicate, class Lock=std::mutex>
void wait(std::unique_lock<Lock> &lock, Predicate pred);
Edit 编辑
As explained by @Lingxi, and further pointed out by @TC, the absolutely correct and very simple solution here is to use condition_variable_any
, which was designed for stuff like this. 如@Lingxi所解释,并由@TC进一步指出,此处绝对正确且非常简单的解决方案是使用
condition_variable_any
,它是针对此类内容设计的。
Try std::condition_variable_any
. 尝试
std::condition_variable_any
。 It has a template version of wait
. 它具有
wait
的模板版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.