使用std :: mutex复制类 [英] Copy Class with std::mutex

查看:468
本文介绍了使用std :: mutex复制类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以std :: mutex作为成员的类。我正在尝试创建此类数组的数组

I have a class with a std::mutex as a member. I am trying to create an array of such class

class C
{
 int x;
 std::mutex m;
};

int main()
{
  C c[10];
  //later trying to create a temp C
  C temp = c[0];
}

由于互斥对象不可复制,因此上述操作显然不可行。解决这个问题的方法是通过复制构造函数。

Clearly the above is not possible as mutex object is not copyable. The way to solve it is through a copy constructor.

但是,在创建复制构造函数时遇到了问题。我已经尝试过

However, I am having problem in creating a copy constructor. I have tried

C (const C &c)
{
   x = c.x;

   //1. m
   //2. m()
   //3. m = c.m
}

我不确定3种语法中正确的语法是什么选择。请帮忙。

I am not sure what is the right syntax out of the 3 choices. Please help.

推荐答案

简短的答案是您不复制互斥锁。

Short answer you dont copy the mutex.

让我们从基础开始,互斥体是互斥的简称,即您要确保在有多个线程时不希望它们并行更改/修改值。您希望序列化访问或修改/读取,以便读取的值有效。

Lets start from the basics, mutex is a short name of mutual exclusion i.e you want to make sure that, when there are multiple threads you dont want them to change/modify the value in parallel. You want to serialize the access or modification/read so that the value read is valid.

在上述情况下,您要将新值复制到变量。创建新对象时无需使用互斥锁。

In the above case you are copying a new value to the variable.In this case you need not use a mutex lock as you are creating a new object.

这篇关于使用std :: mutex复制类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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