std::thread 사용시
- 반드시 join 또는 detach 해야한다.
std::jthread
- C++20 에서 추가된 새로운 스레드 클래스
- <thread>
- 소멸자에서 join을 해준다.
#include <thread>
#inlcude <iostream>
#include <chrono>
using namespace std::literals;
void foo(int a, double b) {
std::cout << "start foo" << std::endl;
std::this_thread::sleep_for(2s);
std::cout << "finish foo" << std::endl;
}
int main() {
std::jthread t(foo, 10, 3.4);
}
jthread에서 stop token 예제
#include <chrono>
#include <iostream>
#include <thread>
using namespace std::literals;
void foo() {
for (int i = 0 ; i < 10 ; i++) {
std::this_thread::sleep_for(500ms);
std::cout << "foo : " << i << std::endl;
}
}
void goo(std::stop_token token) {
for (int i = 0 ; i < 10 ; i++) {
if (token.stop_requested())
{
std::cout << "stop!" << std::endl;
return;
}
std::this_thread::sleep_for(500ms);
std::cout << "foo : " << i << std::endl;
}
}
int main() {
std::jthread j1(foo);
std::jthread j2(goo); // goo에 std::stop_token인자를 주지 않아도 됨.
std::this_thread::sleep_for(2s);
j1.request_stop();
j2.request_stop();
}
728x90
'Language > C++' 카테고리의 다른 글
[C++] std::async (0) | 2024.12.20 |
---|---|
[C++] std::packaged_task (0) | 2024.12.18 |
[C++] std::promise, std::future (0) | 2024.12.04 |
[C++] std::ref, std::reference_wrapper (1) | 2023.09.01 |
[C++] std::thread (0) | 2023.09.01 |
댓글