c++ - 复制带有互斥量的 ctor 作为数据成员

标签 c++ mutex

对于以互斥作为成员的类,当我创建复制构造函数时,我需要决定锁定哪个互斥。对于下面的代码,我想知道为什么我只需要锁定rhs.mu_而不必锁定this->mu_?是否有可能多个线程为同一个对象调用复制构造函数?

class Obj {
 public:
  std::mutex mu_;
  std::string data_;

  // copy ctor
  Obj(const Obj& rhs) {
    std::unique_lock<std::mutex> lk(rhs.mu_); // why only lock rhs.mu_?
    data_ = rhs.data_;
  }
}

更新: 这段代码是否在使用new的同时调用了copy ctor?

Obj* t = nullptr;
Obj someObj;

// ... populate someObj

std::thread t1([&]() { t = new Obj(someObj); });
std::thread t2([&]() { t = new Obj(someObj); });

最佳答案

如果你的变量是局部变量,在构造过程中其他线程无法访问它,因为其他线程不能命名本线程中的局部变量。

如果您的变量具有静态生命周期,则线程安全由 C++ 标准保证:

[stmt.dcl]

Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration;

...

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

因此构造函数不会被调用两次。

关于c++ - 复制带有互斥量的 ctor 作为数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576514/

相关文章:

c++ - 重新学习opengl

c++ - 为什么调用带有成员数组的 constexpr 函数不是常量表达式?

bash - 如何在 Linux 上使用 flock

linux - 实现互斥体?

c++ - TBB和其他库中的线程池模式

c++ - 将 vector::iterator 分配给 char 数组后 VS 2003

c++ - 整数作为 8 传递给函数,但函数内部的值是 -439854520

multithreading - 当使用来自 `fork` 创建的多个 C 线程的回调函数时,Rust Mutex 不工作

c++ - boost::mutex 在模板中使用时不起作用

c++ - QReadWriteLock递归