Gus*_*avo 2 c++ multithreading c++11
在问题Using QSqlQuery from multiple thread中,结果是线程存储解决了问题。
我制作了一个简单的演示代码,以绝对清楚 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();
}
Run Code Online (Sandbox Code Playgroud)
如果对象被构造,它将在线程函数退出时被销毁。几乎是在[basic.stc.thread]/2上的那些确切的话:
具有线程存储持续时间的变量应在首次 odr 使用([basic.def.odr])之前初始化,并且如果构造,应在线程退出时销毁。