2011-07-26 2 views
4

C++에서 ThreadLocal을 구현하는 가장 좋은 방법은 누구라도 필요에 따라 전달할 값을 설정하고 가져올 수 있다는 것입니다.C++ ThreadLocal 구현

나는 위키피디아에서 ThreaLocal에 관해 읽고 있었다.

C++ 0x는 thread_local 키워드를 도입합니다.

사람이 gcc가 이것에 대한 선언과 아마 그 사용법을 알고 있습니까 : 그 외에, 다양한 C++ 컴파일러 구현은 스레드 로컬 변수를 선언하는 구체적인 방법을 제공?

답변

3

이것은 대개 OS가 사용하는 스레딩 라이브러리의 일부입니다. 리눅스에서 스레드 로컬 저장소는 pthread_key_create, pthread_get_specificpthread_set_specific 함수로 처리됩니다. 대부분의 스레딩 라이브러리는 이것을 캡슐화하고 C++ 인터페이스를 제공합니다. 부스트에서는 thread_specific_ptr ...

2

VC10 더 유연하게, 당신에게 같은 일을 제공 combinable라는 이름의 새로운 클래스가 참조하십시오.

3

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_createpthread_[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