小编iTr*_*uth的帖子

为什么线程返回时 thread_local 变量没有被销毁?

为了更好地理解这个问题,代码如下:

// code 1
#include <iostream>
#include <thread>

struct tls_test {
    tls_test()
    { std::cout << "tls_test ctor\n"; }

    ~tls_test()
    { std::cout << "tls_test dtor\n"; }

    void print() const
    { std::cout << "tls_test print\n"; }
};

thread_local tls_test t;

void thread_1()
{
    std::cout << "thread_1 started\n";
    t.print();
    std::cout << "thread_1 return\n";
}

int main()
{
    std::thread trd{ thread_1 };
    trd.join();
    std::cout << "main return\n";
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 TDM-GCC 和 Windows 10 来测试该程序。这是输出:

// code 1
#include <iostream>
#include <thread>

struct tls_test { …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading thread-local stdthread c++17

10
推荐指数
0
解决办法
324
查看次数

标签 统计

c++ ×1

c++17 ×1

multithreading ×1

stdthread ×1

thread-local ×1