Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Class with std::mutex

Tags:

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 } 

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

like image 483
bhavesh Avatar asked May 20 '15 03:05

bhavesh


People also ask

Can you copy a mutex C++?

std::mutex::mutexmutex objects cannot be copied/moved (both the copy constructor and assignment operator are deleted for this type).

Can you copy std :: mutex?

std::mutex is neither copyable nor movable.

Can std :: mutex be moved?

On the other hand, while right now std::mutex is not movable, it is very easy to 'return' one from a function: return an std::unique_ptr<std::mutex> instead. This still pays the costs of dynamic allocation but only in one spot.

Are mutexes fair?

Mutexes can be fair or unfair. A fair mutex lets threads through in the order they arrived. Fair mutexes avoid starving threads.


1 Answers

You shouldn't write any of these lines. Your implementation of copy constructor is equivalent to:

C (const C &c) : x(), m() {    x = c.x; } 

So new instance of mutex m is default initialized which means that one of the default constructors will be called. It may be safely used.

However, there are several conserns about this code. I.e. if m protects x, you should explicitly lock it before accessing value:

C (const C &c) {     std::lock_guard<std::mutex> (c.m);     x = c.x; } 

which would require to declare m as mutable (because c is const reference in copy ctor).

mutable std::mutex m; 

In the end, you can see that copying objects with mutexes inside is confusing, and if C is public class, it'll confuse its users, so think twice before implementing copying of it.

like image 101
myaut Avatar answered Sep 17 '22 03:09

myaut