쓰레드를 생성하는 방법
1. std::thread의 생성자로 쓰레드로 수행할 함수 전달.
2. <thread> 헤더 필요
3. 객체의 생성이 곧 thread start이다.
4. join()이나 detach()를 해야한다.
- join() : 쓰레드 종료를 대기
- detach() : 쓰레드를 떼어 냄 (생성된 쓰레드가 독립적으로 실행)
std::thread usage
#include <thread>
void f1() {};
void f2(int a, double d) {}
void f3(int a, int& b, std::string&& s) {b = 100;}
int main() {
int n = 0;
std::string s = "hello";
std::thread t1(&f1);
std::thread t2(&f2, 10, 3.4);
std::thread t3(&f3, 10, std::ref(n), std::move(s));
t1.join();
t2.join();
t3.join();
}
위와 같이 thread 함수에 인자를 전달하는 방법은 두가지 이다.
- lvalue reference = std::ref() 사용
- rvalue reference = std::move() 사용
thread와 callable object
- std::thread의 인자로 일반함수 뿐만아니라, 멤버함수/함수객체/람다표현식 등을 전달할 수 있다.
- 맴버함수를 thread의 인자로 넘길경우 객체까지 같이 넘겨야 한다.
#include <thread>
struct Adder {
void Add(int a, int b) {}
};
int main () {
Adder a;
std::thread t(&Adder::Add, &a, 1, 3);
t.join();
}
thread member
member type
- native_handle_type : native_handle() 멤버함수의 반환 타입
member class
- id : thread id 담는 타입
member functions
- hardware_concurrency : cpu가 지원하는 thread 개수
- get_id : thread id 반환
- native_handle : OS의 쓰레드 핸들 반환
- swap : 쓰레드 Object swap
#include <thread>
void foo() {}
void goo() {}
int main () {
std::thread t1(&foo);
std::thread t2(&goo);
t1.swap(t2); // t1과 t2가 실행하는 함수가 바뀜.
std::thread t3 = t1; // error
std::thread t4 = std::move(t1); // ok
t1.join(); // 13번째 줄에서 move했기 때문에 해당 라인은 예외발생
t2.join(); // foo실행
t4.join(); // goo실행
}
- joinable : join이 가능한지 여부 조사
- join : 쓰레드 종료 대기
- detach : 쓰레드 떼어내기
728x90
'Language > C++' 카테고리의 다른 글
[C++] std::promise, std::future (0) | 2024.12.04 |
---|---|
[C++] std::ref, std::reference_wrapper (1) | 2023.09.01 |
[C++] std::chrono (0) | 2023.09.01 |
[C++] std::this_thread (0) | 2023.09.01 |
[C++] 난수 생성하기 (0) | 2023.07.21 |
댓글