Let's say I have multiple threads and each of them is trying to create objects of the same class.
Will the simultaneous creation of objects of the same type in different threads interfere with each other?
Do I need to use "lock" within the constructor?
This depends very much on the implementation of the constructor.
If the constructor is only accessing members of that class, and not any external static classes or methods, then yes - it is thread safe.
But if that constructor is accessing non-threadsafe objects that exist outside of the class itself, (such as a global singleton), then it is not threadsafe.
update: The constructor should be careful not to access any static members of the class that are not readonly or const. (thanks Nathan A and LVBen)
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