1
질문에서 Using QSqlQuery from multiple threads에는 스레드 저장이 문제를 해결한다는 결과가있었습니다.thread_local 객체의 파손
C++ 11 thread_local 지정자에 대한 간단한 데모 코드를 작성했습니다. 아래 코드는 ThreadLocal 객체를 로컬 고유 객체로 갖는 두 개의 스레드를 만듭니다. 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();
}