#include <iostream>
#include <thread>
void f1() {
for(int i=0; i<10; i++)
std::cout << "t1()" << std::endl;
}
void f2() {
for(int i=0; i<10; i++)
std::cout << "t2()" << std::endl;
}
void f3() {
for(int i=0; i<10; i++)
std::cout << "t3()" << std::endl;
}
int main() {
std::thread t1(f1);
std::thread t2(f2);
std::thread t3(f3);
t1.join();
t2.join();
t3.join();
return 0;
}
스레드 예제 1
C++에서 스레드는 thread 헤더파일에 선언되어 있으며, thread name(function); 과 같은 꼴로 정의할 수 있다.
정의한 스레드는 join()메서드나 detach() 메서드를 호출하지 않고 소멸될 경우 예외를 뱉어내게 된다.
join 메서드
thread::join() 메서드는 쓰레드가 종료되고 나서 리턴하는 함수다. 즉 t1.join()은 t1이 끝나기 전에는 리턴하지 않기 때문에 다음 구문을 실행하지 않는다.
detach 메서드
thread::detach() 메서드는 join() 메서드처럼 쓰레드가 종료될 때 까지 기다리는 것이 아니라 그냥 내버려 두는 메서드라고 보면 된다. detach()를 하게 되면 main 함수가 종료될 경우(main thread가 죽을 경우) 다른 모든 스레드(worker thread라고 많이 함)도 모두 죽게 된다.
스레드의 return 값?
스레드는 따로 return 값이라는것을 갖지 않는다. 만약 thread에서 계산한 어떤 값을 main스레드에서 확인하고 싶으면 포인터의 형태로 제공해서 가져와야 한다.
스레드에 파라미터를 전달하는 법
using std;
void add(vector<int>::iterator start, vector<int>::iteraotr end, int* result) {
int sum = 0;
for(auto itr = start; itr != end; itr++)
sum += *itr;
*result = sum;
}
int main() {
vector<int> data(10000);
for(int i=0; i<10000; i++) {
data[i] = i;
}
vector<int> partial_sums(4);
vector<thread> workers;
for(int i=0; i<4; i++) {
workers.push_back(thread(add, data.begin() + i * 2500,
data.begin() + (i + 1) * 2500,
&partial_sums[i]
));
}
for(int i=0; i<4; i++) {
workers[i].join();
}
int result = 0;
for(int i=0; i<4; i++) {
result += partial_sums[i];
}
cout << result << endl;
return 0;
}
스레드의 생성자에 스레드가 실행할 함수/함수 객체와, 그 뒤에 함수가 실행할 파라미터를 전달하면 파라미터를 스레드에 전달할 수 있다.
'프로그래밍 언어 > C++' 카테고리의 다른 글
C++ / std::atomic (0) | 2023.02.17 |
---|---|
C++ 11 / mutex를 활용한 동기화 (0) | 2023.02.16 |
C++ / std::function (0) | 2023.02.16 |
C++ 11 / 스마트 포인터 shared_ptr, weak_ptr (0) | 2023.02.15 |
C++ 11 / 스마트 포인터 unique_ptr (0) | 2023.02.15 |
댓글