質問Using QSqlQuery from multiple threadsには、スレッドストレージが問題を解決するという結果がありました。thread_localオブジェクトの破壊
シンプルなデモコードを作成して、C++ 11 thread_local指定子について完全に明確にしました。次のコードは、ローカル一意オブジェクトとしてThreadLocalオブジェクトを持つ2つのスレッドを作成します。 Storage :: get関数は、スレッド固有のシングルトンです。標準では、ThreadLocalデストラクタがスレッド関数のジョインまたは終了時に呼び出されることを保証していますか?オブジェクトが構築された場合GCC 5.4.0 (G ++ -o主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();
}