c++ - thread_local 对象的销毁

标签 c++ multithreading c++11

在问题Using QSqlQuery from multiple threads结果是线程存储解决了这个问题。

我制作了一个简单的演示代码,以绝对清楚 C++11 thread_local 说明符。下面的代码创建了两个线程,它们将 ThreadLocal 对象作为本地唯一对象。 Storage::get 函数是线程特定的单例。标准是否保证在加入或退出线程函数时调用 ThreadLocal 析构函数?

使用 GCC 5.4.0 编译 (g++ -o main main.cpp --std=c++11 -lpthread)

#include <thread>
#include <mutex>
#include <string>
#include <chrono>
#include <iostream>
#include <atomic>

static std::mutex mtx;

struct ThreadLocal {
    std::string name;

    ~ThreadLocal() {
        mtx.lock();
        std::cout << "destroy " << name << std::endl;
        mtx.unlock();
    }
};

struct Storage {
    static ThreadLocal &get() {
        /* Thread local singleton */
        static thread_local ThreadLocal l;
        static std::atomic<int> cnt(0);
        l.name = std::to_string(cnt);
        cnt++;
        return l;
    }
};

void thread() {
    mtx.lock();
    std::cout << Storage::get().name << std::endl;
    mtx.unlock();
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main(int argc, const char **argv) {
    std::thread t1(&thread);
    std::thread t2(&thread);
    t1.join();
    t2.join();
}

最佳答案

如果对象被构建,它将在线程函数退出时销毁。几乎在 [basic.stc.thread]/2 上的那些确切的话:

A variable with thread storage duration shall be initialized before its first odr-use ([basic.def.odr]) and, if constructed, shall be destroyed on thread exit.

关于c++ - thread_local 对象的销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498215/

相关文章:

c++ - 在 C++ 中对代数结构矩阵使用类的开销

c++ - 带有 VK_NULL_HANDLE 的 Vulkan DestroyInstance/DestroyDevice

c++ - 什么是默认方法以及如何正确使用它们?

c++ - 尝试在C++中为chrono创建函数时没有构造函数实例

c++ - std::shared_ptr 的用法

java - ConcurrentHashMap 支持的队列的线程安全

java - Spring:从 Web 应用程序线程子线程(来自 ThreadPool)访问请求( session )作用域 Bean

java - 2D volatile 数组 : will self-assignment help or do I need AtomicIntegerArray?

c++ - 基于范围的for循环中的未命名循环变量?

c++ - 如何在 C++ 中使父类(super class)的虚函数可被孙子覆盖?