thread_local 키워드를 이용하여.
같은 이름을 가지지만 스레드마다 다른 전용 변수를 만들 수 있습니다.
사용 예1 전역 변수
- #include <iostream>
- #include <thread>
-
- thread_local int abc = 1;
-
- void func()
- {
- std::cout << abc << '\n';
- }
-
- void main()
- {
- ++abc; //주 스레드의 abc 변수값 1 증가 (값 2)
-
- std::thread th(func);
- th.join(); // 다른 스레드에서의 func 출력
결과 1
-
- func(); //주 스레드의 func 출력 결과 2
- }
|
사용 예2 지역 변수
지역변수에 thread_local 키워드를 붙인다면
static을 붙이지 않아도 static 속성이 적용됩니다.
- #include <iostream>
- #include <thread>
-
- void func()
- {
- thread_local int abc = 1; //thread_local static int abc = 1; 과 같음
- std::cout << abc++ << '\n';
- }
-
- void func2()
- {
- func();
- func();
- }
-
- void main()
- {
- std::thread th(func2);
- th.join(); // 다른 스레드에서의 func2 출력
결과 1 2
- func2(); //주 스레드의 func 출력 결과 1 2
- }
|
사용 예3 static 멤버 변수
- #include <iostream>
- #include <thread>
-
- class A
- {
- public:
- thread_local static int abc;
- };
- thread_local int A::abc = 1;
-
-
- void func()
- {
- std::cout << A::abc++ << '\n';
- }
-
- void func2()
- {
- func();
- func();
- }
-
- void main()
- {
- std::thread th(func2);
- th.join(); // 다른 스레드에서의 func2 출력
결과 1 2
- func2(); //주 스레드의 func 출력 결과 1 2
- }
|
댓글 없음:
댓글 쓰기