[C++] jthread
Updated:
개요
- thread와 일반적으로는 동일
- destruction 시 자동으로 다시 join
- 특정 상황에서 중지 가능
- 공유 중지 상태를 유지하는 stop_source 타입의 private 멤버를 내부적으로 가짐
- 생성자는 stop_token을 첫 번째 인수로 사용하는 함수를 허용
- 함수는 실행 중에 중지가 요청되었는지 확인하고 요청된 경우 반환 가능
- 멤버 함수
- stop token handling
- get_stop_source()
- 스레드의 공유 중지 상태와 관련된 stop_source 객체를 반환
- get_stop_token()
- 스레드의 공유 중지 상태와 관련된 stop_token을 반환
- request_stop()
- 스레드의 공유 중지 상태를 통해 실행 중지를 요청
- destruction 시 request_stop()를 호출하고 이미 호출 했다면 무시
- get_stop_source()
- stop token handling
예제
- 코드
#include <chrono> #include <iostream> #include <thread> using namespace std; int main() { auto test1 = []() { // automatically rejoins on destruction jthread([]() { cout << "1" << endl; }); }; test1(); cout << endl << "------" << endl << endl; auto test2 = []() { jthread t([](stop_token token) { cout << "1" << endl; using namespace chrono_literals; this_thread::sleep_for(1s); if (token.stop_requested()) { cout << "stop" << endl; return; } cout << 2 << endl; }); cout << 3 << endl; t.join(); }; test2(); cout << endl << "------" << endl << endl; auto test3 = []() { jthread t([](stop_token token) { cout << "1" << endl; using namespace chrono_literals; this_thread::sleep_for(1s); if (token.stop_requested()) { cout << "stop" << endl; return; } cout << 2 << endl; }); t.request_stop(); t.join(); cout << 3 << endl; }; test3(); return 0; }
- 실행 결과
1 ------ 3 1 2 ------ 1 stop 3