Namespaces
Variants

std::jthread:: get_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
std:: stop_token get_stop_token ( ) const noexcept ;
(自 C++20 起)

返回一个 std::stop_token ,该令牌与 jthread 对象内部持有的共享停止状态相关联。

参数

(无)

返回值

一个类型为 std::stop_token 的值,与 jthread 对象内部持有的停止状态相关联。

示例

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string_view>
#include <thread>
using namespace std::chrono_literals;
void print(std::string_view name, const std::stop_token& token)
{
    std::cout << name << ": stop_possible = " << token.stop_possible();
    std::cout << ", stop_requested = " << token.stop_requested() << '\n';
}
void finite_sleepy(std::stop_token stoken)
{
    for (int i = 10; i; --i)
    {
        std::this_thread::sleep_for(300ms);
        if (stoken.stop_requested())
        {
            std::cout << "  睡眠工作线程收到停止请求\n";
            return;
        }
        std::cout << "  睡眠工作线程继续休眠\n";
    }
}
void infinite_sleepy()
{
    for (int i = 5; i; --i)
    {
        std::this_thread::sleep_for(300ms);
        std::cout << "  按需持续运行\n";
    }
}
int main()
{
    std::cout << std::boolalpha;
    // 一个会监听停止请求的工作线程
    std::jthread stop_worker(finite_sleepy);
    // 一个仅在完成时停止的工作线程
    std::jthread inf_worker(infinite_sleepy);
    std::stop_token def_token;
    std::stop_token stop_token = stop_worker.get_stop_token();
    std::stop_token inf_token = inf_worker.get_stop_token();
    print("def_token ", def_token);
    print("stop_token", stop_token);
    print("inf_token ", inf_token);
    std::cout << "\n请求并加入 stop_worker:\n";
    stop_worker.request_stop();
    stop_worker.join();
    std::cout << "\n请求并加入 inf_worker:\n";
    inf_worker.request_stop();
    inf_worker.join();
    std::cout << '\n';
    print("def_token ", def_token);
    print("stop_token", stop_token);
    print("inf_token ", inf_token);
}

可能的输出:

def_token : stop_possible = false, stop_requested = false
stop_token: stop_possible = true, stop_requested = false
inf_token : stop_possible = true, stop_requested = false
请求并加入 stop_worker:
  按需持续运行
  睡眠工作线程收到停止请求
请求并加入 inf_worker:
  按需持续运行
  按需持续运行
  按需持续运行
  按需持续运行
def_token : stop_possible = false, stop_requested = false
stop_token: stop_possible = true, stop_requested = true
inf_token : stop_possible = true, stop_requested = true