Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::jthread::jthread

      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
       
       
      jthread()noexcept;
      (1)(since C++20)
      jthread( jthread&& other)noexcept;
      (2)(since C++20)
      template<class F,class...Args>
      explicit jthread( F&& f, Args&&...args);
      (3)(since C++20)
      jthread(const jthread&)= delete;
      (4)(since C++20)

      Constructs newstd::jthread object.

      1) Creates newstd::jthread object which does not represent a thread.
      2) Move constructor. Constructs thestd::jthread object to represent the thread of execution that was represented byother. After this callother no longer represents a thread of execution.
      3) Creates newstd::jthread object and associates it with a thread of execution.

      The new thread of execution starts executing:

      std::invoke(decay-copy(std::forward<F>(f)), get_stop_token(),
                  decay-copy(std::forward<Args>(args))...)
      (until C++23)

      std::invoke(auto(std::forward<F>(f)), get_stop_token(),
                 auto(std::forward<Args>(args))...)

      (since C++23)

      if the expression above is well-formed, otherwise starts executing:

      std::invoke(decay-copy(std::forward<F>(f)),
                  decay-copy(std::forward<Args>(args))...)
      .
      (until C++23)

      std::invoke(auto(std::forward<F>(f)),
                 auto(std::forward<Args>(args))...)
      .

      (since C++23)
      The calls ofdecay-copy are evaluated(until C++23)The values produced byauto arematerialized(since C++23) in the current thread, so that any exceptions thrown during evaluation and copying/moving of the arguments are thrown in the current thread, without starting the new thread.
      These overloads participate in overload resolution only ifstd::remove_cvref_t<F> is not the same type asstd::jthread.
      If any of the following isfalse, the program is ill-formed:
      The completion of the invocation of the constructorsynchronizes with the beginning of the invocation of the copy off on the new thread of execution.
      4) The copy constructor is deleted; threads are not copyable. No twostd::jthread objects may represent the same thread of execution.

      Contents

      [edit]Parameters

      other - anotherstd::jthread object to construct thisstd::jthread object with
      f -Callable object to execute in the new thread
      args - arguments to pass to the new function

      [edit]Postconditions

      1)get_id() equal tostd::jthread::id() (i.e.joinable() returnsfalse) andget_stop_source().stop_possible() isfalse.
      2)other.get_id() equal tostd::jthread::id() andget_id() returns the value ofother.get_id() prior to the start of construction.
      3)get_id() not equal tostd::jthread::id() (i.e.joinable() returnstrue), andget_stop_source().stop_possible() istrue.

      [edit]Exceptions

      3)std::system_error if the thread could not be started. The exception may represent the error conditionstd::errc::resource_unavailable_try_again or another implementation-specific error condition.

      [edit]Notes

      The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. withstd::ref orstd::cref).

      Any return value from the function is ignored. If the function throws an exception,std::terminate is called. In order to pass return values or exceptions back to the calling thread,std::promise orstd::async may be used.

      [edit]Example

      Run this code
      #include <chrono>#include <iostream>#include <thread>#include <utility> usingnamespace std::literals; void f1(int n){for(int i=0; i<5;++i){std::cout<<"Thread 1 executing\n";++n;std::this_thread::sleep_for(10ms);}} void f2(int& n){for(int i=0; i<5;++i){std::cout<<"Thread 2 executing\n";++n;std::this_thread::sleep_for(10ms);}} class foo{public:void bar(){for(int i=0; i<5;++i){std::cout<<"Thread 3 executing\n";++n;std::this_thread::sleep_for(10ms);}}int n=0;}; class baz{public:void operator()(){for(int i=0; i<5;++i){std::cout<<"Thread 4 executing\n";++n;std::this_thread::sleep_for(10ms);}}int n=0;}; int main(){int n=0;    foo f;    baz b;std::jthread t0;// t0 is not a threadstd::jthread t1(f1, n+1);// pass by valuestd::jthread t2a(f2,std::ref(n));// pass by referencestd::jthread t2b(std::move(t2a));// t2b is now running f2(). t2a is no longer a threadstd::jthread t3(&foo::bar,&f);// t3 runs foo::bar() on object fstd::jthread t4(b);// t4 runs baz::operator() on a copy of object b    t1.join();    t2b.join();    t3.join();std::cout<<"Final value of n is "<< n<<'\n';std::cout<<"Final value of f.n (foo::n) is "<< f.n<<'\n';std::cout<<"Final value of b.n (baz::n) is "<< b.n<<'\n';// t4 joins on destruction}

      Possible output:

      Thread 2 executingThread 1 executingThread 4 executingThread 3 executingThread 3 executingThread 4 executingThread 2 executingThread 1 executingThread 3 executingThread 1 executingThread 4 executingThread 2 executingThread 3 executingThread 1 executingThread 4 executingThread 2 executingThread 3 executingThread 1 executingThread 4 executingThread 2 executingFinal value of n is 5Final value of f.n (foo::n) is 5Final value of b.n (baz::n) is 0

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 3476C++20overload(3) directly required (the decayed types of)
      F and the argument types to be move constructible
      removed these
      requirements[1]
      1. The move-constructibility is already indirectly required bystd::is_constructible_v.

      [edit]See also

      constructs newthread object
      (public member function ofstd::thread)[edit]
      C documentation forthrd_create
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/jthread/jthread&oldid=172094"

      [8]ページ先頭

      ©2009-2025 Movatter.jp