名前空間
変種
操作

std::jthread::get_stop_source

From 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)
future
(C++11)
(C++11)
(C++11)
(C++11)
安全なメモリ解放 (Safe Reclamation)
(C++26)
ハザードポインタ
アトミック型
(C++11)
(C++20)
アトミック型の初期化
(C++11)(C++20で非推奨)
(C++11)(C++20で非推奨)
メモリオーダー
(C++11)(C++26で非推奨)
アトミック操作のためのフリー関数
アトミックフラグのためのフリー関数
 
 
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
English 日本語 中文(简体) 中文(繁體)