Programming/CPP11&14
[C++11] Storage class specifiers에 thread_local 추가
psychoria
2015. 7. 7. 19:00
반응형
Storage class specifiers는 기존에 register, static, extern, auto가 존재했습니다.
auto는 의미가 없기 때문에 C++11에서는 다른 용도로 사용됩니다.
2014/12/10 - [Programming/C++11&14] - [C++11] auto 키워드
C++11에는 thread를 지원하기 위해서 thread_local이 추가되었습니다.
TLS(Thread Local Storage)를 지원하기 위해서 사용됩니다.
하나의 변수를 선언하면 각각의 thread에 별도로 적용됩니다.
thread_local은 Visual Studio 2013은 지원하지 않고 Visual Studio 2015부터 지원합니다.
thread_local은 다음과 같이 사용하면 됩니다.
#include <iostream>
#include <thread>
#include <mutex>
thread_local unsigned int i = 0;
std::mutex mtx;
void ThreadFunc(int nID)
{
++i;
std::unique_lock<std::mutex> lock(mtx);
std::cout << nID << "-thread : " << i << std::endl;
}
int main()
{
std::thread th1(ThreadFunc, 0), th2(ThreadFunc, 1);
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Main thread : " << i << std::endl;
lock.unlock();
th1.join();
th2.join();
return 0;
}
전역 변수에 thread_local을 지정했습니다.
그리고 각 thread에서 해당 변수를 증가시키고 main에서는 원래 값을 출력합니다.
결과는 다음과 같이 출력됩니다.
Main thread : 0 0-thread : 1 1-thread : 1 |
전역 변수에 thread_local 키워드가 추가되면 각각의 thread에 별개로 적용되는 것을 확인할 수 있습니다.
각각의 thread에서 사용할 변수를 생성할 때 유용하게 사용이 가능합니다.
반응형