-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(c++/multi-thread-programming): add thread_local examples
- Loading branch information
1 parent
c56daae
commit 1bbb8ca
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
#include <iostream> | ||
#include <vector> | ||
#include <thread> | ||
#include <atomic> | ||
|
||
using namespace std; | ||
|
||
// 각 쓰레드 단위로 접근 가능한 전역변수 취급 | ||
thread_local int LThreadId = 0; | ||
|
||
void ThreadMain(int threadId) | ||
{ | ||
// 쓰레드 단위로 값 할당. 다른 쓰레드에 영향 미치지 않음. | ||
LThreadId = threadId; | ||
|
||
while (true) | ||
{ | ||
cout << LThreadId << endl; | ||
this_thread::sleep_for(std::chrono::milliseconds(1000)); | ||
} | ||
} | ||
|
||
int main() | ||
{ | ||
vector<thread> threads; | ||
for (int i = 0; i < 10; i++) | ||
{ | ||
int threadId = i + 1; | ||
threads.push_back(thread(ThreadMain, threadId)); | ||
} | ||
for (thread& t : threads) | ||
{ | ||
t.join(); | ||
} | ||
} |