gpt4 book ai didi

c++ - 在 C++ 中是否可以进行热切的 thread_local 初始化?

转载 作者:太空狗 更新时间:2023-10-29 23:11:00 42 4
gpt4 key购买 nike

[basic.stc.thread] 声明“具有线程存储持续时间的变量应在其第一次 odr-use (6.2) 之前初始化,如果构造,则应在线程退出时销毁。 "

这是否会阻止实现在线程创建时急切地初始化命名空间范围的 thread_local 变量,是否有任何主要编译器支持通过某些注释强制执行此操作的机制?

我有非常少量的性能关键型 __thread vars 我想避免 thread_local 通常会产生的每次访问延迟初始化检查,但我目前需要通过单独的调用进行设置/拆卸,以保持在对非平凡析构函数等的 __thread 限制内。每个线程都没有惰性初始化测试?

否则,处理 __thread setup/teardown 调用注册的最简洁的已知模式是什么?

最佳答案

Can I get thread_local with guaranteed eager construction/destruction for every thread and no lazy init testing?

不太可能。

Failing that, what is the cleanest known pattern for dealing with __thread setup/teardown call registration?

您可以将所有特定于线程的信息打包到一个对象中,该对象通过一个特定于线程的指针访问,该指针在线程启动时被初始化。例如:

struct ThreadContext {
thread_local static ThreadContext* instance;

ThreadContext() {
assert(!instance);
instance = this;
}

~ThreadContext() {
instance = 0;
}

ThreadContext(ThreadContext const&) = delete;
ThreadContext& operator=(ThreadContext const&) = delete;
};

thread_local ThreadContext* ThreadContext::instance = 0;

void thread_function() {
ThreadContext context;

// Access it elsewhere as:
ThreadContext::instance;
}

ThreadContext* getThisThreadContext() {
return ThreadContext::instance;
// No init check here. Just one move:
// mov rax, QWORD PTR fs:ThreadContext::instance@tpoff
}

关于c++ - 在 C++ 中是否可以进行热切的 thread_local 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52760481/

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