c++ Lock class 骨架

c++ Lock class skeleton

来自 Effective STL(Scott Meyers)第 12 项,下面是 c++ 锁的框架 class。

template<typename Container>
class Lock {
public:
    Lock(const Container& container)
    : c(container)
    {
        getMutexFor(c);
    }

    ~Lock()
    {
        releaseMutexFor(c);
    }
private:
    const Container& c;
};

我不明白的一点是为什么互斥量是在锁的 c 私有成员上获取的(它本身是从我们要锁定的容器中复制构造的)。

以下是否会有效地锁定 v(以及为什么)?

vector<int> v;
{
    Lock<vector<int> > lock(v);
    ...
}

谢谢。

The point I do not understand is why the mutex is acquired on the lock's c private member (itself copy-constructed from the container we want to take a lock on).

c 是对传递给锁的构造函数的容器的 引用 ,而不是副本。所以同一个容器被锁定了。

Will the following effectively lock v (and why)?

vector<int> v;
{
    Lock<vector<int> > lock(v);
    ...
}

是的,v 将被锁定在 {} 定义的范围内(当然,前提是锁定机制已正确实现。)

请注意,只有当访问 v 的所有其他代码都锁定了同一个互斥锁时,此锁才有用,例如,通过遵循使用锁守卫的相同约定。

另见 std::lock_guard

重点是 c 不是复制构造的,它是 reference.

实际上是一个引用,正如@juanchopanza 所说,传递给构造函数的对象也是如此。相对于第二个问题,"Will the following effectively lock v (and why)?"我觉得不是。这是一个示例,Container 必须是一个特殊的 class,它包含一个互斥量。我们需要查看其余代码。但据我所知,vector 没有内部互斥锁。