命名空间
变体
操作

std::jthread::get_stop_source

来自 cppreference.com
< cpp‎ | thread‎ | jthread
 
 
并发支持库
线程
(C++11)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
协作取消
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
闩锁和屏障
(C++20)
(C++20)
期货
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危险指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 中已弃用)
(C++11)(C++20 中已弃用)
内存排序
原子操作的自由函数
原子标志的自由函数
 
 
std::stop_source get_stop_source() noexcept;
(自 C++20 起)

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

[编辑] 参数

(无)

[编辑] 返回值

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

[编辑] 示例

#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';
    };
 
    // A worker thread
    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 << "  Sleepy worker is requested to stop\n";
                return;
            }
            std::cout << "  Sleepy worker goes back to sleep\n";
        }
    });
 
    std::stop_source stop_source = worker.get_stop_source();
    print("stop_source", stop_source);
 
    std::cout << "\nPass source to other thread:\n";
    auto stopper = std::thread(
        [](std::stop_source source)
        {
            std::this_thread::sleep_for(500ms);
            std::cout << "Request stop for worker via source\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
 
Pass source to other thread:
  Sleepy worker goes back to sleep
Request stop for worker via source
  Sleepy worker is requested to stop
 
stop_source: stop_possible = true, stop_requested = true