Namespaces
Variants

std:: stop_token

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
헤더에 정의됨 <stop_token>
class stop_token ;
(C++20부터)

stop_token 클래스는 연결된 std::stop_source 객체에 대해 중지 요청이 있었는지 또는 가능한지 확인하는 수단을 제공합니다. 이는 본질적으로 연결된 중지 상태에 대한 스레드 안전한 "뷰"입니다.

stop_token std::stop_callback 의 생성자에도 전달될 수 있으며, 이 경우 stop_token 과 연관된 std::stop_source 에 정지 요청이 발생하면 콜백이 호출됩니다. 또한 stop_token std::condition_variable_any 의 인터럽트 가능 대기 함수에 전달되어, 정지 요청 시 조건 변수의 대기를 중단할 수 있습니다.

목차

멤버 별칭 템플릿

유형 정의
callback_type < Callback > (C++26부터) std:: stop_callback < Callback >

멤버 함수

새로운 stop_token 객체를 생성합니다
(public member function)
stop_token 객체를 소멸합니다
(public member function)
stop_token 객체를 할당합니다
(public member function)
수정자
두 개의 stop_token 객체를 교환합니다
(public member function)
관찰자
연결된 중지 상태에 중지 요청이 있었는지 확인합니다
(public member function)
연결된 중지 상태에 중지 요청이 가능한지 확인합니다
(public member function)

비멤버 함수

(C++20)
두 개의 std::stop_token 객체를 비교함
(함수)
std::swap 알고리즘을 특수화함
(함수)

참고 사항

stop_token 객체는 일반적으로 독립적으로 생성되지 않고, std::jthread 또는 std::stop_source 로부터 획득됩니다. 이로 인해 std::jthread 또는 std::stop_source 와 동일한 연관된 중지 상태를 공유하게 됩니다.

기능 테스트 매크로 표준 기능
__cpp_lib_jthread 201911L (C++20) Stop token joining thread

예제

#include <iostream>
#include <thread>
using namespace std::literals::chrono_literals;
void f(std::stop_token stop_token, int value)
{
    while (!stop_token.stop_requested())
    {
        std::cout << value++ << ' ' << std::flush;
        std::this_thread::sleep_for(200ms);
    }
    std::cout << std::endl;
}
int main()
{
    std::jthread thread(f, 5); // 약 3초 동안 5 6 7 8...을 출력합니다
    std::this_thread::sleep_for(3s);
    // jthread의 소멸자는 request_stop()과 join()을 호출합니다.
}

가능한 출력:

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19