Do I need mutex in the constructor for the field?

Suppose 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() to modify the value of this field. doit() will be called from multiple threads. If I only have a mutex in the doit() method, is that enough? Do I have a guarantee that I will never read an uninitialized field (because there is no lock in the constructor)?

Edit: I was probably not clear enough. Is there a problem with the processor cache or something similar? I mean, if there is no mutex to initialize a memory region (i.e., My field) - is there a risk that another thread will read some garbage value?

+8
c ++ mutex
source share
3 answers

Your object can be initialized only once, and you cannot use it until it is initialized, so you do not need a mutex. However, you will need a mutex or other suitable lock in your DoIt function, since, as you said, it will be available for multiple threads.

Update for editable question: No, you do not need to worry about the processor cache. You must first create your object before you can get a handle to it. Only once, when you have this descriptor, you can transfer it to other flows which will be used. I am trying to say that the generated threads should begin after the creation of the original object, this is not possible for this to happen the other way around!

+7
source share

It is not possible to call doit() on an object that has not yet been created, so you do not need a 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 this field, even from a single thread, then you should also use the mutex in these methods.

+2
source share
  • First you need to construct the object before these annoying streams take on it. The OS will allocate memory for the constructor, which is called only by one thread. Ths OS monitors this distribution, and so you don’t have to do anything. Hell, you can even create two objects of the same class in two different threads.
  • You can be very conservative and use the mutex at the beginning of any method that used this field to lock it, and release it and the end.

Or, if you understand the interactions of different methods with different algorithms, you can use the mutex for critical sections of code that use this field - i.e. this part of the code must be sure that the field will not be changed by another thread during processing, but you can release the lock after a critical section, do something else, perhaps another critical section.

0
source share

All Articles