gcc를 사용하면 __thread
을 사용하여 스레드 로컬 변수를 선언 할 수 있습니다. 그러나 이는 초기화 된 이니시에이터가있는 POD 유형에만 국한되며 모든 플랫폼에서 사용할 수있는 것은 아닙니다 (Linux 및 Windows에서 모두 사용할 수 있지만). 당신이 thread_local
사용하는 것처럼 당신은 변수 선언의 일부로 사용
__thread int i=0;
i=6; // modify i for the current thread
int* pi=&i; // take a pointer to the value for the current thread
POSIX 시스템에서 당신이 직접 관리 스레드 로컬 데이터에 액세스 할 수 pthread_key_create
및 pthread_[sg]et_specific
을 사용할 수 있으며, Windows에서 당신은 TlsAlloc
을 사용할 수 있습니다 같은쪽에 Tls[GS]etValue
일부 라이브러리는 생성자 및 소멸자와 함께 유형을 사용할 수 있도록하는 래퍼를 제공합니다. 예를 들어, boost는 boost::thread_specific_ptr
을 제공하여 각 스레드에 대해 로컬 인 동적 할당 객체를 저장할 수 있으며 just::thread 라이브러리는 thread_local
키워드의 동작을 C++ 0x와 유사하게 모방 한 JSS_THREAD_LOCAL
매크로를 제공합니다.
사용 부스트 :
boost::thread_specific_ptr<std::string> s;
s.reset(new std::string("hello")); // this value is local to the current thread
*s+=" world"; // modify the value for the current thread
std::string* ps=s.get(); // take a pointer to the value for the current thread
또는 그냥 :: 스레드를 사용하여 :
JSS_THREAD_LOCAL(std::string,s,("hello")); // s is initialised to "hello" on each thread
s+=" world"; // value can be used just as any other variable of its type
std::string* ps=&s; // take a pointer to the value for the current thread