使用 thread_local 计数线程

huangapple go评论54阅读模式
英文:

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 &lt;atomic&gt;
#include &lt;mutex&gt;

class ThreadCounter
{
	static inline std::atomic&lt;std::size_t&gt; thread_count = 0;
	static thread_local ThreadCounter instance;

	ThreadCounter()
	{
		++thread_count;
	}
	~ThreadCounter()
	{
		--thread_count;
	}

public:
	static size_t get()
	{
		return thread_count;
	}
};

#include &lt;iostream&gt;

int main()
{
	std::cout &lt;&lt; ThreadCounter::get() &lt;&lt; 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.

huangapple
  • 本文由 发表于 2023年6月16日 04:24:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定