Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ constructors and concurrency

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?

like image 541
ThomasMcLeod Avatar asked Jul 24 '12 02:07

ThomasMcLeod


2 Answers

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.

like image 134
Greg Hewgill Avatar answered Sep 21 '22 22:09

Greg Hewgill


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.

like image 24
Ned Batchelder Avatar answered Sep 18 '22 22:09

Ned Batchelder