【问题标题】:thread_local vs local variable in C++ [duplicate]C ++中的thread_local与局部变量[重复]
【发布时间】: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 &lt;&lt; i++ &lt;&lt; " " &lt;&lt; j++ &lt;&lt; std::endl; 添加到您的f 函数中并运行(单个)线程,如下所示:thread t([]{ f(1); f(1); f(1); });。现场演示:wandbox.org/permlink/ZbWGoWOiEDsXkUCE.

标签: c++ multithreading local-variables thread-local


【解决方案1】:

thread_local 在省略static 时暗示static。

当一个给定的函数被多次调用时,一个局部的static 变量会保留它的值。您可以在别处阅读有关 static 变量的信息。

现在,我假设您确实知道 static 变量是什么 - 重要的是:

  • 静态变量具有局部范围
  • (但)静态变量具有全局存在

第二点使其他函数可以通过 C++ 引用和指针访问静态变量的内存 - 它证明静态变量只有一个副本 - 跨进程的所有线程。您需要知道什么是线程以及如何创建/编程线程。

现在,问题来了。您知道 全局 变量具有全局范围和全局可访问性,但是当您运行程序的两个或多个实例时,它们都/全部都将拥有该全局变量的单独副本。这意味着每个进程都将拥有该全局变量的单独副本。

那么,如果您希望每个线程拥有一个单独的 static 变量副本怎么办?你使用thread_static。每个线程都将拥有该静态变量的单独副本。

有趣的是,您也可以将thread_local 应用于全局变量 - 这样每个线程也会收到这些全局变量的单独副本!

// Globals
int counter;
thread_local int this_thread_counter; // Each thread will have separate copy

现在,想想strtok 将如何工作 - 想想对strtok 的(并发)调用!

【讨论】:

  • 您好,澄清一下,您的回答后半部分是指thread_local 而不是thread_static?
猜你喜欢
  • 2013-02-19
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
相关资源
最近更新 更多