thread_local 与 C++ 中的局部变量[重复]

问题描述 投票:0回答:1

有人可以清楚、简单地解释一下 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++ multithreading local-variables thread-local
1个回答
3
投票
当省略

thread_local

 时,
static
意味着
static

局部

static
变量在多次调用给定函数时保留其值。您可以在其他地方阅读有关
static
变量的内容。

现在,我假设您确实知道

static
变量是什么 - 重要的是:

  • 静态变量具有局部作用域
  • (但是)静态变量具有全局存在

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

现在,回答问题。您知道 Global 变量具有全局作用域和全局可访问性,但是当您运行程序的两个或多个实例时,它们/所有实例都将具有该全局变量的单独副本。这意味着每个进程都会有该全局变量的单独副本。

那么,如果您想为每个线程拥有一个单独的

static
变量副本怎么办?您使用
thread_local
。每个线程都会有该静态变量的单独副本。

有趣的是,您也可以将

thread_local 
应用于全局变量 - 这样每个线程也将收到这些全局变量的单独副本!

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

现在,思考

strtok
将如何工作 - 考虑对
strtok
的(并发)调用!

© www.soinside.com 2019 - 2024. All rights reserved.