I've been thinking about writing a container class to control access to a complex data structure that will have use in a multi-threaded environment.
And then the question occurred to me:
Is there ever a situation where c++ constructors must be thread-safe?
In general, a constructor cannot be called for the same object by two threads simultaneously. However, the same constructor can certainly be called for different objects at the same time.
Certainly you can invoke the same constructor from more than one thread at once. It that sense, they must be thread-safe, just as any other function must be. If the constructor is going to modify shared state, for example, your container, then you must use synchronization to ensure that the state is modified in a deterministic way.
You can't construct the same object on more than one thread at once, because each object is only constructed once, so there's no way to invoke the constructor on the same object more than once, much less on two different threads at the same time.
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