thread_local 变量何时以及如何初始化和销毁​​?

When and how are thread_local variables initialized and destroyed?

在我的代码中使用它之前,我想更好地理解 thread_local

比方说,我声明

thread_local myclass value;

那将为每个使用 value 的线程创建 myclass 的新实例?线程退出时会发生什么?该实例会被释放还是会保留在内存中的某个地方?什么时候调用析构函数?

是否thread_local锁定构造函数以便在任何时刻只能调用一个构造函数?

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

不,构造函数调用没有自动同步。 None 是必需的,因为只有一个线程可能会尝试构造给定的线程局部对象。

根据this storage duration reference一个thread_local变量:

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

所以是的,当线程结束时,该线程的 thread_local 变量的生命周期也结束,这意味着这些特定实例将被销毁。