为什么std :: condition_variable不能通过锁类型模板化? [英] Why isn't std::condition_variable templated by lock type?

查看:244
本文介绍了为什么std :: condition_variable不能通过锁类型模板化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试模式下具有断言能力是非常有用的,因为开销相当小,互斥锁是否被锁定。查看已知选项,我选择了实现此选项由于低开销,使用 std :: mutex 子类

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 的超集,因此大多数事情都很好用它。例如, std :: unique_lock 模板化以利用具有特定接口的任何锁类型。

The interface of the subclass is a superset of that of std::mutex, and so most things work well with it. E.g., std::unique_lock is templated to utilize any lock type that has a specific interface.

问题出在 std :: condition_variable ,特别是等待成员,例如:

The problem is with std::condition_variable, in particular the wait members, e.g.:

template<class Predicate>
void wait(std::unique_lock<std::mutex> &lock, Predicate pred);

可以看出,该方法需要非常具体的 unique_lock / mutex 组合。不幸的是, Liskov原则不适用于 container< derived> ; $

As can be seen, the method requires a very specific unique_lock/mutex combination. Unfortunately, also, the Liskov principle doesn't extend for container<derived> being converted into container<base>.

我不明白 / p>

I don't understand


  1. 为什么会这样?

如果意图是强制使用 std :: unique_lock ,那么为什么不能使用以下内容:

Even if the intent was to enforce the use of std::unique_lock, then why couldn't the following be used:

template<class Predicate, class Lock=std::mutex>
void wait(std::unique_lock<Lock> &lock, Predicate pred);




  1. li>
  1. how to reasonably get around this?

编辑

并进一步指出@TC,绝对正确和非常简单的解决方案是使用 <$

As explained by @Lingxi, and further pointed out by @T.C, the absolutely correct and very simple solution here is to use condition_variable_any, which was designed for stuff like this.

推荐答案

这篇关于为什么std :: condition_variable不能通过锁类型模板化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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