【问题标题】:Destruction of thread_local objects销毁 thread_local 对象
【发布时间】:2017-11-26 16:12:51
【问题描述】:

在问题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();
}

【问题讨论】:

    标签: c++ multithreading c++11


    【解决方案1】:

    如果对象被构造,它将在线程函数退出时被销毁。 [basic.stc.thread]/2:

    具有线程存储持续时间的变量应在之前初始化 它的第一次 odr 用途([basic.def.odr]),如果构造,应 在线程退出时销毁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 2013-07-13
      相关资源
      最近更新 更多