简体   繁体   中英

When and how are thread_local variables initialized and destroyed?

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.

According to this storage duration reference a thread_local variable:

... is allocated when the thread begins and deallocated when the thread ends.

So yes, when the thread ends the life-time of thread_local variables for that thread also ends, which means those specific instances will be destructed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM