Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::jthread::get_stop_source

      From cppreference.com
      <cpp‎ |thread‎ |jthread
       
       
      Concurrency support library
      Threads
      (C++11)
      (C++20)
      this_thread namespace
      (C++11)
      (C++11)
      (C++11)
      Cooperative cancellation
      Mutual exclusion
      Generic lock management
      (C++11)
      (C++11)
      (C++11)
      (C++11)
      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;
      (since C++20)

      Returns astd::stop_source associated with the same shared stop-state as held internally by thejthread object.

      [edit]Parameters

      (none)

      [edit]Return value

      A value of typestd::stop_source associated with stop-state held internally byjthread object.

      [edit]Example

      Run this code
      #include <chrono>#include <condition_variable>#include <iostream>#include <mutex>#include <string_view>#include <thread> usingnamespace std::chrono_literals; int main(){std::cout<<std::boolalpha;auto print=[](std::string_view name,conststd::stop_source& source){std::cout<< name<<": stop_possible = "<< source.stop_possible();std::cout<<", stop_requested = "<< source.stop_requested()<<'\n';}; // A worker threadauto 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);}

      Possible output:

      stop_source: stop_possible = true, stop_requested = false Pass source to other thread:  Sleepy worker goes back to sleepRequest stop for worker via source  Sleepy worker is requested to stop stop_source: stop_possible = true, stop_requested = true
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/jthread/get_stop_source&oldid=161151"

      [8]ページ先頭

      ©2009-2025 Movatter.jp