gpt4 book ai didi

c++ - 带有 GCC 的 C++11 中的线程作用域对象

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:46 24 4
gpt4 key购买 nike

考虑以下 C++11 程序:

struct S {
S() {/* do something */ }
} global_object;

int main() {
}

我还没有要测试的 GCC 4.8,但是根据我对 C++11 标准的了解,无论我是否将全局对象声明为 thread_local,对象本身将在程序执行期间为所有可能创建的线程实例化一次。

在 GCC 中有没有一种方法(可移植的或不可移植的)在每次一个线程启动时实例化和构造全局对象,并在同一线程每次结束时销毁?

最佳答案

but from what I read about the C++11 standard, no matter if I declare the global object as thread_local, the object itself will be instantiated once for all the possible threads that can be created during the execution of the program.

这不是 C++11 标准规定的内容。 C++11 标准(草案 n3337)的相关部分:

  • 3.7.2 线程存储持续时间,第 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.

  • 7.1.1 存储类说明符,第 4 条:

The thread_local specifier indicates that the named entity has thread storage duration (3.7.2). It shall be applied only to the names of variables of namespace or block scope and to the names of static data members. When thread_local is applied to a variable of block scope the storage-class-specifier static is implied if it does not appear explicitly.

它没有说明如果一个对象在全局命名空间中用 thread_local 定义,那么只会创建它的一个实例。 Jesse Good 已发布的替代示例打印全局对象的每个实例的唯一地址(参见online demo):

#include <iostream>
#include <thread>
#include <vector>

struct S {};
thread_local S global_s;

int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
threads.push_back(std::thread([](){ std::cout << &global_s << '\n'; }));
for (auto& t: threads) t.join();
}

输出:

0x4165993f0x4205a93f0x4485e93f0x42a5b93f0x4525f93f0x45c6093f0x4666193f0x4706293f0x43e5d93f0x4345c93f

关于c++ - 带有 GCC 的 C++11 中的线程作用域对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17471525/

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