Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
Arsen Zahray Avatar asked Dec 13 '22 08:12

Arsen Zahray


1 Answers

[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.

like image 146
Igor Tandetnik Avatar answered Dec 16 '22 11:12

Igor Tandetnik