C ++重写操作符,用于由多个线程访问其对象的类

时间:2017-05-04 13:44:00

标签: c++ multithreading

我想为一个容器类重载operator =,operator ==,如下所示。容器类对象可以从多个线程访问。

Container& operator=(const Container &other)
{
   // assign this->variable = other.variable
}

我创建了两个容器对象,如下所示

Container objectA, objectB.

如果我从任何一个帖子做objectA = objectB,那么它是否安全 对于objectA,objectB内部的互斥操作,重载的operator =()函数内部如下所示。

Container& operator=(const Container &other)
{
    // take objectA mutex.
    // take objectB mutex.
   // assign this->variable = other.variable
   // release objectB mutex.
   // release objectA mutex.
}

如果有任何推荐或标准方式,请告诉我。

2 个答案:

答案 0 :(得分:1)

我看到你的方法遇到了僵局:

//Thread1:
x = y;

// Thread2:
y = x;

可能会发生这样的事情:

order:
T1: take x.mutex
T2: take y.mutex
T1: take y.mutex (can't, waiting)
T2: take x.mutex (can't, waiting)

oups

答案 1 :(得分:-2)

我不是主线,但如果你不使用互斥锁,你会感到有些惊讶。每个线程可以有一个互斥锁,或者您可以为复制所需的所有变量使用互斥锁

For exemple, here we supposed you need to copy both A & B variable
from the "Other" Container instance

std::mutex ex1 //Mutex for var A & B for your "$this" instance
std::mutex ex2 //Mutex for var A & B for your Other instance

Container& operator=(const Container &other)
{
 ex1.lock();
 ex2.lock();
 $this->A = other.getA();
 $this->B = other.getB();
 ex1.unlock();
 ex2.unlock();
}

只需使用互斥锁"逻辑"变量,如果A,B和C依赖(或同时使用),为它们创建一个互斥锁,而不是为你的类创建一个互斥锁:)