英文:
Counting threads using thread_local
问题
我编写了以下类:
#include <atomic>
#include <mutex>
class ThreadCounter
{
static inline std::atomic<std::size_t> thread_count = 0;
static thread_local ThreadCounter instance;
ThreadCounter()
{
++thread_count;
}
~ThreadCounter()
{
--thread_count;
}
public:
static size_t get()
{
return thread_count;
}
};
我期望它打印出 1,但我看到的是 0。
我假设对于每个启动的线程,instance 都会被构造(我相当确定,因为我一段时间前在另一种情况下观察到了这种行为),并且会增加计数器。然而,返回的值始终为零。
我还尝试将实例放在类外,无论是使用 static thread_local 还是仅使用 thread_local 限定符,无论是在头文件中还是在单独的 .cpp 文件中。但这些方法都没有起作用。
是否有什么方法可以使它工作,还是这种方法不可能?
英文:
I wrote a following class:
#include <atomic>
#include <mutex>
class ThreadCounter
{
static inline std::atomic<std::size_t> thread_count = 0;
static thread_local ThreadCounter instance;
ThreadCounter()
{
++thread_count;
}
~ThreadCounter()
{
--thread_count;
}
public:
static size_t get()
{
return thread_count;
}
};
#include <iostream>
int main()
{
std::cout << ThreadCounter::get() << std::endl;
}
I expect it to print 1, but I see 0.
I assumed that for each thread started, the instance would be constructed (I was quite certain because I observed such behavior some time ago in another case) and increment the counter. However, the value returned is always zero.
I also tried putting the instance outside of the class, both with static t_l and t_l-only specifiers, both in the header and in a separate .cpp file. None of these worked.
Is there some trick to make it work, or is this approach impossible?
答案1
得分: 3
thread_local 变量很奇怪。
全局的 thread_local 变量在你启动一个线程时并不会被构造。相反,它们会在你首次从特定线程访问它们时被构造。
你没有在任何地方访问 instance,因此它没有被构造。
英文:
thread_local variables are weird.
Global thread_local variables are not constructed when you start a thread. Rather, they are constructed when you first access them from a given thread.
You don't access instance anywhere, so it's not constructed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论