티스토리 뷰

TLS 란 무엇인가

스레드가 공유하는 영역은

  • heap 영역 (new)
  • 데이터 영역 (static 변수)

스레드가 개별적으로 잡는 영역은

  • 스택 (함수를 위한)
  • TLS (데이터를 위한, 스레드 본인만의 전역 공간)

이다.

왜 써야할까? 언제 유용할까?

공유변수를 한번 확인하고, 개별 스레드에서 요리조리 하는 상황에 유용할 것이다.

요리조리할때 매번 공유되는 영역을 확인하기 위해서 lock을 잡기보다는, 캐싱해오는 개념이다

네트워크 통신할때 필요한 버퍼가 그 예시이다.

코드

C++ 11 에서 표준 스펙으로 채택되었다 (keyword - https://en.cppreference.com/w/cpp/keyword/thread_local)


  
thread_local int LThreadId = 0;
int main()
{
return 0;
}

스레드에게 ID를 직접 부여해보자


  
#include <iostream>
#include <thread>
#include <vector>
thread_local int LThreadId = 0;
void ThreadMain(int threadId)
{
LThreadId = threadId; // 본인의 TLS 영역에 저장함
while (true)
{
std::cout << "Hi I am Thread " << LThreadId << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
{
int threadId = i + 1;
threads.push_back(std::thread(ThreadMain, threadId));
}
for (std::thread& t : threads)
{
t.join();
}
return 0;
}

 

 

👁️ 만약 thread_local 키워드를 붙이지 않는다면, 원하는 결과를 얻을 수 없다


  
#include <iostream>
#include <thread>
#include <vector>
// thread_local int LThreadId = 0;
int LThreadId = 0;
void ThreadMain(int threadId)
{
LThreadId = threadId; // 본인의 TLS 영역에 저장함
while (true)
{
std::cout << "Hi I am Thread " << LThreadId << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
{
int threadId = i + 1;
threads.push_back(std::thread(ThreadMain, threadId));
}
for (std::thread& t : threads)
{
t.join();
}
return 0;
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함