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?
Mutexes can be fair or unfair. A fair mutex lets threads through in the order they arrived. Fair mutexes avoid starving threads.
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.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With