【发布时间】:2020-01-23 08:19:58
【问题描述】:
有人能清楚简单地解释一下 i 和 j 变量有什么区别吗?
#include <thread>
using namespace std;
void f(int n)
{
thread_local int i = n;
int j = n;
}
int main()
{
thread t1(f, 1);
thread t2(f, 2);
t1.join();
t2.join();
return 0;
}
【问题讨论】:
-
在你的情况下似乎没有区别
-
我没有在 C++ 中比较这两者的任何罚款!我需要知道我应该在哪里使用 thread_local 以及我应该只在传递给线程的函数中使用局部变量。
-
要查看差异,请将
std::cout << i++ << " " << j++ << std::endl;添加到您的f函数中并运行(单个)线程,如下所示:thread t([]{ f(1); f(1); f(1); });。现场演示:wandbox.org/permlink/ZbWGoWOiEDsXkUCE.
标签: c++ multithreading local-variables thread-local