쓰레드마다 갖고 있는 로컬 저장소 != 스택

get_id() 로 받는 난수 id가 아닌 쓰레드마다 직접 id를 할당하고 싶다면?thread_local int32 LThreadId = 0; //TLS
mutex m;
void ThreadMain(int32 threadId)
{
LThreadId = threadId;
while(true)
{
{
lock_guard<mutex> lock(m);
cout << "Hi! I am Thread " << LThreadId << endl;
}
this_thread::sleep_for(1s);
}
}
int main()
{
vector<thread> threads;
for(int32 i = 0 ; i < 10 ; i++)
{
int32 threadId = i + 1;
threads.push_back(thread(ThreadMain, threadId));
}
for (thread& t : threads)
t.join();
return 0;
}
실행 결과
Hi! I am Thread 1
Hi! I am Thread 4
Hi! I am Thread 2
Hi! I am Thread 5
Hi! I am Thread 3
Hi! I am Thread 6
Hi! I am Thread 8
Hi! I am Thread 7
Hi! I am Thread 9
Hi! I am Thread 10
...