I'd like to better understand thread_local
before I use it in my code.
Let's say, I declare
thread_local myclass value;
That will create new instance of myclass
for each thread that is using the value
? What happens when the thread exits? Will the instance be freed or is it going to remain somewhere in the memory? When will be called the destructor?
Does thread_local
lock the constructor so that only one can be called at any moment in time?
[basic.stc.thread]/1 All variables declared with the
thread_local
keyword have thread storage duration. The storage for these entities shall last for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread.[basic.stc.thread]/2 A variable with thread storage duration shall be initialized before its first odr-use (6.2) and, if constructed, shall be destroyed on thread exit.
No, there is no automatic synchronization for the constructor call. None is needed, as only one thread can possibly attempt to construct a given thread-local object.
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