Namespaces
Variants

std:: stop_callback

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
(C++20)
stop_callback
(C++20)
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>
template < class Callback >
class stop_callback ;
(C++20부터)

stop_callback 클래스 템플릿은 연결된 std::stop_token 객체에 대한 콜백 함수를 등록하는 RAII 객체 타입을 제공하며, 콜백 함수는 std::stop_token 의 연결된 std::stop_source 가 정지 요청을 받을 때 호출됩니다.

stop_callback 의 생성자를 통해 등록된 콜백 함수들은 다음 두 경우 중 하나에서 호출됩니다: 동일한 스레드에서 stop_callback 의 연관된 std::stop_token std::stop_source 에 대해 request_stop ( ) 를 성공적으로 호출하는 경우; 또는 생성자의 등록 이전에 이미 정지가 요청된 상태라면, 콜백은 stop_callback 을 생성하는 스레드에서 호출됩니다.

동일한 stop_callback 에 대해 둘 이상 생성될 수 있으며, 동일한 스레드 또는 다른 스레드에서 동시에 생성될 수 있습니다. 실행 순서에 대한 보장은 제공되지 않지만, 콜백들은 동기적으로 호출됩니다. 단, 이전에 설명된 바와 같이 std::stop_token 에 대해 중단이 이미 요청된 후 생성된 stop_callback 은 예외입니다.

콜백 호출이 예외를 통해 종료되면 std::terminate 가 호출됩니다.

std::stop_callback CopyConstructible , CopyAssignable , MoveConstructible , MoveAssignable 가 아닙니다.

템플릿 매개변수 Callback 타입은 반드시 invocable 이면서 destructible 이어야 합니다. 모든 반환 값은 무시됩니다.

목차

멤버 타입

유형 정의
callback_type Callback

멤버 함수

새로운 stop_callback 객체를 생성합니다
(public member function)
stop_callback 객체를 소멸시킵니다
(public member function)
operator=
[deleted]
stop_callback 은 할당할 수 없습니다
(public member function)

추론 가이드

예제

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
using namespace std::chrono_literals;
// 원자적 std::cout 스트리밍을 위한 헬퍼 클래스 사용
class Writer
{
    std::ostringstream buffer;
public:
    ~Writer()
    {
        std::cout << buffer.str();
    }
    Writer& operator<<(auto input)
    {
        buffer << input;
        return *this;
    }
};
int main()
{
    // 작업자 스레드
    // 중지 요청이 있을 때까지 대기합니다
    std::jthread worker([] (std::stop_token stoken)
    {
        Writer() << "Worker thread's id: " << std::this_thread::get_id() << '\n';
        std::mutex mutex;
        std::unique_lock lock(mutex);
        std::condition_variable_any().wait(lock, stoken,
            [&stoken] { return stoken.stop_requested(); });
    });
    // 작업자 스레드에 중지 콜백 등록
    std::stop_callback callback(worker.get_stop_token(), []
    {
        Writer() << "Stop callback executed by thread: "
            << std::this_thread::get_id() << '\n';
    });
    // stop_callback 객체는 실행을 방지하기 위해 조기에 소멸될 수 있습니다
    {
        std::stop_callback scoped_callback(worker.get_stop_token(), []
        {
            // 이 코드는 실행되지 않습니다
            Writer() << "Scoped stop callback executed by thread: "
                << std::this_thread::get_id() << '\n';
        });
    }
    // stop_callback을 실행하는 스레드와 시점을 보여줍니다
    // 중지 함수 정의
    auto stopper_func = [&worker]
    {
        if (worker.request_stop())
            Writer() << "Stop request executed by thread: "
                << std::this_thread::get_id() << '\n';
        else
            Writer() << "Stop request not executed by thread: "
                << std::this_thread::get_id() << '\n';
    };
    // 여러 스레드가 작업자 스레드 중지를 위해 경쟁하도록 합니다
    std::jthread stopper1(stopper_func);
    std::jthread stopper2(stopper_func);
    stopper1.join();
    stopper2.join();
    // 중지가 이미 요청된 후에는
    // 새로운 stop_callback이 즉시 실행됩니다
    Writer() << "Main thread: " << std::this_thread::get_id() << '\n';
    std::stop_callback callback_after_stop(worker.get_stop_token(), []
    {
        Writer() << "Stop callback executed by thread: "
            << std::this_thread::get_id() << '\n';
    });
}

가능한 출력:

Worker thread's id: 140460265039616
Stop callback executed by thread: 140460256646912
Stop request executed by thread: 140460256646912
Stop request not executed by thread: 140460248254208
Main thread: 140460265043776
Stop callback executed by thread: 140460265043776