简体   繁体   English

为什么std :: condition_variable没有按锁类型进行模板化?

[英]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 我不明白

  1. why this is so? 为什么会这样呢?

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);
  1. how to reasonably get around this? 如何合理地解决这个问题?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM