목록

2019년 7월 7일 일요일

[C++] thread_local 스레드 지역 변수



thread_local 키워드를 이용하여.
같은 이름을 가지지만 스레드마다 다른 전용 변수를 만들 수 있습니다.

사용 예1 전역 변수
  1. #include <iostream>
  2. #include <thread>
  3.  
  4. thread_local int abc = 1;
  5.  
  6. void func()
  7. {
  8.         std::cout << abc << '\n';
  9. }
  10.  
  11. void main()
  12. {
  13.         ++abc; //주 스레드의 abc 변수값 1 증가 ( 2)
  14.  
  15.         std::thread th(func);
  16.         th.join(); // 다른 스레드에서의 func 출력 결과 1
  17.  
  18.         func(); //주 스레드의 func 출력 결과 2
  19. }

사용 예2 지역 변수
지역변수에 thread_local 키워드를 붙인다면
static을 붙이지 않아도 static 속성이 적용됩니다.


  1. #include <iostream>
  2. #include <thread>
  3.  
  4. void func()
  5. {
  6.         thread_local int abc = 1; //thread_local static int abc = 1; 과 같음
  7.         std::cout << abc++ << '\n';
  8. }
  9.  
  10. void func2()
  11. {
  12.         func();
  13.         func();
  14. }
  15.  
  16. void main()
  17. {
  18.         std::thread th(func2);
  19.         th.join(); // 다른 스레드에서의 func2 출력 결과 1 2
  20.         func2(); //주 스레드의 func 출력 결과 1 2
  21. }



사용 예3 static 멤버 변수

  1. #include <iostream>
  2. #include <thread>
  3.  
  4. class A
  5. {
  6. public:
  7.         thread_local static int abc;
  8. };
  9. thread_local int A::abc = 1;
  10.  
  11.  
  12. void func()
  13. {
  14.         std::cout << A::abc++ << '\n';
  15. }
  16.  
  17. void func2()
  18. {
  19.         func();
  20.         func();
  21. }
  22.  
  23. void main()
  24. {
  25.         std::thread th(func2);
  26.         th.join(); // 다른 스레드에서의 func2 출력 결과 1 2
  27.         func2(); //주 스레드의 func 출력 결과 1 2
  28. }







댓글 없음:

댓글 쓰기

목록