我试图使类的复制构造函数线程安全,如下所示:
class Base
{
public:
Base ( Base const & other )
{
std::lock_guard<std::mutex> lock ( other.m_Mutex );
...
}
protected:
std::mutex m_Mutex;
}
class Derived : public Base
{
public:
Derived ( Derived const & other ) : Base ( other )
{
std::lock_guard<std::mutex> lock ( other.m_Mutex );
...
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在派生类中,我需要在初始化列表中的基类构造函数调用之前锁定互斥体,以保证一致性。知道我如何才能实现这一目标吗?
问候。
@AnthonyWilliams 的建议是将构造函数锁定为委托构造函数的参数,请参阅此处查看完整文章:
class A
{
private:
A(const A &a, const std::lock_guard<std::mutex> &)
: i(a.i), i_squared(a.i_squared) {}
public:
A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {}
...
};
Run Code Online (Sandbox Code Playgroud)
请注意,您锁定另一个对象是为了防止它在复制期间被另一个线程更改(对象本身的构造是安全的)。此外,相同的方法对于移动构造函数也有效。
您的示例的应用程序可能如下所示(未经测试和未编译):
class Base
{
public:
Base(Base const& other) : Base(other, std::lock_guard<std::mutex>(other.m_Mutex)) {}
virtual ~Base() = default; //virtual destructor!
protected:
Base(Base const& other, std::lock_guard<std::mutex> const&) {}
mutable std::mutex m_Mutex; //should be mutable in order to be lockable from const-ref
};
class Derived : public Base
{
protected:
Derived(Derived const& other, std::lock_guard<std::mutex> const& lock)
: Base(other, lock)
{}
public:
Derived(Derived const& other)
: Derived(other, std::lock_guard<std::mutex>(other.m_Mutex))
{}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |