gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:03:04 26 4
gpt4 key购买 nike

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

比方说,我声明

thread_local myclass value;

这将为每个使用 myclass 的线程创建 value 的新实例?当线程退出时会发生什么?实例会被释放还是会保留在内存中的某个地方?什么时候会被称为析构函数?
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.



不,构造函数调用没有自动同步。不需要,因为只有一个线程可以尝试构造给定的线程本地对象。

关于c++ - thread_local 变量何时以及如何初始化和销毁​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61992789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com