cpp thread
include <thread>
+간단한 thread 예
void func() { cout << "aaa" << endl ; }
thread t(&func) ; // func함수가 쓰레드로 실행.
t.join() ; // thread t가 종료 될때 까지 기다림.
+ thread 함수에 파라미터 주기
void func(int x) {..} ;
thread t1(&func, 10) ;
thread t2(&func, 20) ;
t1.join() ;
t2.join() ;
+global 변수를 다중 thread로 카운팅하기
std::atomic<int> global_cnt(0) ; // atomic 하게 작업.
void increase_global(int n) {
for (int i=0; i<n; i++) ++global_cnt;
}
std::vector<std::thread> threads ;
for (int i=0; i<5; i++)
threads.push_back( std::thread( increase_global, 100) ) ;
// 5개의 쓰레드로 100번씩 돌림. global_cnt=>500
+다른 방식
void increase_ref(std::atomic<int> &v , int n) {
for (int i=0; i<n; i++) ++v;
}
std::atomic<int> foo(0) ;
for (int i=0; i<5; i++)
threads.push_back( std::thread( increase_ref, std::ref(foo), 100) ) ;
'Develop > C&CPP' 카테고리의 다른 글
cstring (0) | 2018.06.11 |
---|---|
thread mutex (0) | 2018.06.10 |
utility (0) | 2018.06.08 |
fstream 1 basic_ifstream (0) | 2018.06.07 |
functional 1 plus,minus,bind1st, bind2nd, equal_to, greater (0) | 2018.06.07 |