stop_source — std::stop_source

stop_source — std::stop_source

std::stop_source 클래스는 중지 요청을 내리는 수단을 제공해요 — 예를 들어 std::jthread 취소를 위해. 하나의 stop_source 객체에 대해 내린 중지 요청은, 그와 연관된 모든 stop_sourcestd::stop_token에 보여요. C++20에서 도입됐어요. <stop_token> 헤더에 있어요.

출처: cppreference

본문

// <stop_token> 헤더, C++20
class stop_source;

사용 예 — 수동 중지

#include <stop_token>
#include <thread>
#include <iostream>

void worker(std::stop_token st) {
    while (!st.stop_requested()) {
        std::cout << "working\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main() {
    std::stop_source source;
    std::jthread t(worker, source.get_token());

    std::this_thread::sleep_for(std::chrono::milliseconds(350));
    source.request_stop();    // 중지 요청 → worker의 st에 반영
}

주요 멤버

멤버 설명
get_token() 연관 std::stop_token 반환
request_stop() 중지 요청 (가능하면 true)
stop_requested() 이미 중지 요청했는지
stop_possible() 중지 가능한지

동작

  • request_stop()을 호출하면 중지 상태가 "요청됨"으로 바뀌고, 이 소스로 만든 모든 토큰에서 stop_requested()true가 돼요.
  • 중지 요청이 등록된 stop_callback들을 호출해요.
  • jthread는 내부적으로 자기 stop_source를 가져요 (t.request_stop()).
std::stop_source s1, s2 = s1;    // 같은 상태 공유
s1.request_stop();
// s2.stop_requested()도 true

std::stop_sourcestd::jthread·std::stop_token의 협조적 중지에서 "중지를 요청하는 쪽"이에요. 여러 곳에 토큰을 나눠주고, 소스에서 중지를 내리면 모두에 전파돼요.

더 알아보기 (Learn more)

cppreference