Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need mutex in constructor for field?

Tags:

c++

mutex

Let's assume I have a simple class A with one field in C++. This field is initialized in the constructor. Class A also has a method called doit() for modifing the value of this field. doit() will be called from multiple threads. If I have a mutex only in the doit() method, is this sufficient? Do I have a guarantee that I will never read an uninitialized field (because there is no lock in the constructor)?

Edit: I probably was not clear enough. Is there no issue involving processor cache or something similar? I mean, if there is no mutex for initializing memory region (i.e. my field) - is there no risk that the other thread will read some garbage value?

like image 245
kgs Avatar asked Oct 12 '12 10:10

kgs


People also ask

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.

Why mutex is used in C++?

Mutex is used to provide synchronization in C++ which means only one thread can access the object at the same time, By the use of Mutex keyword we can lock our object from being accessed by multiple threads at the same time.

Are mutexes movable?

By design, std::mutex is not movable nor copyable. This means that a class A holding a mutex won't receive a default move constructor.

What does a mutex do?

In computer programming, a mutex (mutual exclusion object) is a program object that is created so that multiple program thread can take turns sharing the same resource, such as access to a file.


2 Answers

Your object can only be initialised once, and you won't be able use it before it's initialised, so you don't need a mutex there. You will however need a mutex or other suitable lock in your DoIt function, as you said this will be accessed across multiple threads.

Update for edited question: No, you don't need to worry about processor cache. You must construct your object first, before you can have a handle to it. Only once you have this handle can you pass it to other threads to be used. What I'm trying to say is, the spawned threads must start after the construction of the original object, it is impossible for it to happen the other way around!

like image 113
Mark Ingram Avatar answered Oct 09 '22 10:10

Mark Ingram


It is not possible to call doit() on an object that is not created yet, so you do not need mutex in the constructor.

If doit() is the only method that accesses the field, then you should be fine.

If other methods of your class also access that field, even from a single thread, then you must use a mutex also in these methods.

like image 28
Gildas Avatar answered Oct 09 '22 09:10

Gildas