Namespaces
Variants

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

返回一个与 jthread 对象内部持有的共享停止状态相关联的 std::stop_source

参数

(无)

返回值

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

示例

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string_view>
#include <thread>
using namespace std::chrono_literals;
int main()
{
    std::cout << std::boolalpha;
    auto print = [](std::string_view name, const std::stop_source& source)
    {
        std::cout << name << ": stop_possible = " << source.stop_possible();
        std::cout << ", stop_requested = " << source.stop_requested() << '\n';
    };
    // 工作线程
    auto worker = std::jthread([](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";
        }
    });
    std::stop_source stop_source = worker.get_stop_source();
    print("stop_source", stop_source);
    std::cout << "\n将源传递给其他线程:\n";
    auto stopper = std::thread(
        [](std::stop_source source)
        {
            std::this_thread::sleep_for(500ms);
            std::cout << "通过源请求停止工作线程\n";
            source.request_stop();
        },
        stop_source);
    stopper.join();
    std::this_thread::sleep_for(200ms);
    std::cout << '\n';
    print("stop_source", stop_source);
}

可能的输出:

stop_source: stop_possible = true, stop_requested = false
将源传递给其他线程:
  睡眠工作线程继续休眠
通过源请求停止工作线程
  睡眠工作线程被请求停止
stop_source: stop_possible = true, stop_requested = true