销毁thread_local对象 [英] Destruction of thread_local objects

查看:315
本文介绍了销毁thread_local对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在问题从多个线程使用QSqlQuery 时,结果表明线程存储解决了问题。

In the question Using QSqlQuery from multiple threads there was the outcome that thread storage solves the problem.

我编写了一个简单的演示代码,以明确了解C ++ 11 thread_local说明符。下面的代码创建两个线程,这些线程具有ThreadLocal对象作为本地唯一对象。 Storage :: get函数是特定于线程的单例。标准是否保证在连接或退出线程函数时调用ThreadLocal析构函数?

I made a simple demo code to be absolutely clear about C++11 thread_local specifier. The code below creates two threads which have ThreadLocal object as a local unique object. The Storage::get function is a thread specific singleton. Does the standard guarantee that ThreadLocal destructor is called on join or the exit of the thread function?

与GCC 5.4.0
一起编译(g ++ -o main main.cpp --std = c ++ 11 -lpthread)

Compiled with 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

If the object was constructed, it will be destroyed on the exit of the thread function. Pretty much in those exact words over at [basic.stc.thread]/2:


具有线程存储持续时间的变量应在
首次使用odr之前初始化( [basic.def.odr]),并且如果构造了
,则在线程退出时将其销毁。

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.

这篇关于销毁thread_local对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆