【发布时间】: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