클래스에서 스레드 등록을 원하므로 thread_local기능 검사를 추가하기로 결정했습니다 .
#include <iostream>
#include <thread>
class Foo {
public:
Foo() {
std::cout << "Foo()" << std::endl;
}
~Foo() {
std::cout << "~Foo()" << std::endl;
}
};
class Bar {
public:
Bar() {
std::cout << "Bar()" << std::endl;
//foo;
}
~Bar() {
std::cout << "~Bar()" << std::endl;
}
private:
static thread_local Foo foo;
};
thread_local Foo Bar::foo;
void worker() {
{
std::cout << "enter block" << std::endl;
Bar bar1;
Bar bar2;
std::cout << "exit block" << std::endl;
}
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
t1.join();
t2.join();
std::cout << "thread died" << std::endl;
}
코드는 간단하다. 내 Bar클래스에는 정적 thread_local멤버가 foo있습니다. 정적 thread_local Foo foo이 작성되면 스레드가 작성되었음을 의미합니다.
그러나 코드를 실행할 때 Foo()인쇄물에 아무것도 없으며을 Bar사용하는 생성자 에서 주석을 제거 foo하면 코드가 올바르게 작동합니다.
나는 GCC (7.4.0)와 Clang (6.0.0)에서 이것을 시도했으며 결과는 동일합니다. 컴파일러 foo가 사용되지 않은 것을 발견 하고 인스턴스를 생성하지 않는다고 생각합니다. 그래서
- 컴파일러가
static thread_local멤버를 무시 했습니까 ? 이것을 어떻게 디버깅 할 수 있습니까? - 그렇다면 왜 일반
static회원에게이 문제가없는 것입니까?