Namespaces
Variants

std:: stop_source

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_source ;
(C++20 이후)

stop_source 클래스는 std::jthread 취소와 같은 중지 요청을 발행하는 수단을 제공합니다. 하나의 stop_source 객체에 대해 수행된 중지 요청은 동일한 연관된 중지 상태를 가진 모든 stop_source std::stop_token 에게 표시됩니다; 연관된 std::stop_token 에 등록된 모든 std::stop_callback 이 호출되며, 연관된 std::stop_token 을 기다리는 모든 std::condition_variable_any 객체가 깨어납니다.

중지가 요청되면, 이를 취소할 수 없습니다. 추가적인 중지 요청은 아무런 영향을 미치지 않습니다.

목차

멤버 함수

새로운 stop_source 객체를 생성함
(public member function)
stop_source 객체를 소멸시킴
(public member function)
stop_source 객체를 할당함
(public member function)
수정자
연결된 stop-state에 대한 중단 요청을 생성함 (존재하는 경우)
(public member function)
두 개의 stop_source 객체를 교환함
(public member function)
관찰자
연결된 stop-state에 대한 stop_token 을 반환함
(public member function)
연결된 stop-state에 중단 요청이 발생했는지 확인함
(public member function)
연결된 stop-state에 중단 요청이 가능한지 확인함
(public member function)

비멤버 함수

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

헬퍼 태그

stop_source 가 생성 시 관련된 중단 상태를 가지지 않음을 나타내는 태그
(태그)

참고 사항

std::jthread 취소를 목적으로 하여 stop_source 객체는 std::jthread 객체로부터 get_stop_source() 를 사용하여 획득해야 합니다; 또는 중지 요청은 std::jthread 객체로부터 직접 request_stop() 를 사용하여 요청해야 합니다. 이렇게 하면 std::jthread 의 호출된 함수 인수(즉, 해당 스레드에서 실행 중인 함수)에 전달된 것과 동일한 연관된 중지 상태가 사용됩니다.

다른 용도로는, 기본 생성자를 사용하여 별도로 stop_source 를 생성할 수 있으며, 이는 새로운 중지 상태를 생성합니다.

기능 테스트 매크로 표준 기능
__cpp_lib_jthread 201911L (C++20) 중지 토큰 조인 스레드

예제

#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>
using namespace std::chrono_literals;
void worker_fun(int id, std::stop_token stoken)
{ 
    for (int i = 10; i; --i)
    {
        std::this_thread::sleep_for(300ms);
        if (stoken.stop_requested())
        {
            std::printf("  worker%d is requested to stop\n", id);
            return;
        }
        std::printf("  worker%d goes back to sleep\n", id);
    }
}
int main()
{
    std::jthread threads[4];
    std::cout << std::boolalpha;
    auto print = [](const std::stop_source& source)
    {
        std::printf("stop_source stop_possible = %s, stop_requested = %s\n",
                    source.stop_possible() ? "true" : "false",
                    source.stop_requested() ? "true" : "false");
    };
    // 공통 소스
    std::stop_source stop_source;
    print(stop_source);
    // 작업자 스레드 생성
    for (int i = 0; i < 4; ++i)
        threads[i] = std::jthread(worker_fun, i + 1, stop_source.get_token());
    std::this_thread::sleep_for(500ms);
    std::puts("중지 요청");
    stop_source.request_stop();
    print(stop_source);
    // 참고: jthread의 소멸자가 join을 호출하므로 명시적 호출이 필요 없음
}

가능한 출력:

stop_source stop_possible = true, stop_requested = false
  worker2 goes back to sleep
  worker3 goes back to sleep
  worker1 goes back to sleep
  worker4 goes back to sleep
중지 요청
stop_source stop_possible = true, stop_requested = true
  worker3 is requested to stop
  worker1 is requested to stop
  worker2 is requested to stop
  worker4 is requested to stop