Reputation: 205
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?
Upvotes: 8
Views: 2305
Reputation: 359
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)
Upvotes: 19