jthread — std::jthread

jthread — std::jthread

std::jthread 클래스는 단일 실행 스레드 하나를 나타내요. C++20에서 도입됐어요. <thread> 헤더에 있어요.

std::thread와 같은 일반 동작을 가지지만, jthread파괴 시 자동으로 재join되고, 특정 상황에서 취소/중지(stop)될 수 있어요.

출처: cppreference

본문

// <thread> 헤더, C++20
class jthread;

스레드는 관련 jthread 객체의 생성과 동시에 즉시 실행을 시작해요 (보류 중인 OS 스케줄링 지연 후).

파괴 시 자동 join

#include <thread>
#include <iostream>

void worker() { std::cout << "working\n"; }

int main() {
    std::jthread t(worker);   // 실행 시작
    // main 끝나면서 t가 자동 join됨 — std::thread와 달리 join() 불필요
}

std::thread는 파괴 시 join()이나 detach()를 호출하지 않으면 std::terminate가 돼요. jthread는 소멸자에서 자동으로 join()해 이 실수를 방지해요.

중지(Stop) 지원

jthread는 협조적 중지(cooperative cancellation)를 위해 get_stop_source()get_stop_token()을 제공해요.

#include <thread>
#include <chrono>
#include <iostream>

void task(std::stop_token st) {
    while (!st.stop_requested()) {
        // 작업 수행
        std::cout << "running\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    std::cout << "stopped\n";
}

int main() {
    std::jthread t(task);
    std::this_thread::sleep_for(std::chrono::milliseconds(350));
    t.request_stop();       // 중지 요청
    // t.join()은 자동
}

주요 API

멤버 설명
request_stop() 중지 요청
get_stop_source() std::stop_source 획득
get_stop_token() std::stop_token 획득
기타 thread와 동일 join(), detach(), get_id(), joinable()

std::jthread는 실행 스레드의 수명을 안전하게 관리하고(자동 join), 협조적 중지를 기본 제공하는 현대 C++의 스레드 타입이에요. std::thread보다 안전해 새 코드에서 권장돼요.

더 알아보기 (Learn more)

cppreference