Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::call_once

      From cppreference.com
      <cpp‎ |thread
       
       
      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)
      call_once
      (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
       
      Defined in header<mutex>
      template<class Callable,class...Args>
      void call_once(std::once_flag& flag, Callable&& f, Args&&...args);
      (since C++11)

      Executes theCallable objectf exactly once, even if called concurrently from several threads.

      In detail:

      • If, by the timestd::call_once is called,flag indicates thatf was already called,std::call_once returns right away (such a call tostd::call_once is known aspassive).
      • Otherwise,std::call_once callsINVOKE(std::forward<Callable>(f),std::forward<Args>(args)...). Unlike thestd::thread constructor orstd::async, the arguments are not moved or copied because they do not need to be transferred to another thread of execution (such a call tostd::call_once is known asactive).
      • If that invocation throws an exception, it is propagated to the caller ofstd::call_once, andflag is not flipped so that another call will be attempted (such a call tostd::call_once is known asexceptional ).
      • If that invocation returns normally (such a call tostd::call_once is known asreturning),flag is flipped, and all other calls tostd::call_once with the sameflag are guaranteed to bepassive.

      Allactive calls on the sameflag form a single total order consisting of zero or moreexceptional calls, followed by onereturning call. The end of eachactive call synchronizes-with the nextactive call in that order.

      The return from thereturning call synchronizes-with the returns from allpassive calls on the sameflag: this means that all concurrent calls tostd::call_once are guaranteed to observe any side-effects made by theactive call, with no additional synchronization.

      Contents

      [edit]Parameters

      flag - an object, for which exactly one function gets executed
      f -Callable object to invoke
      args... - arguments to pass to the function

      [edit]Return value

      (none)

      [edit]Exceptions

      • std::system_error if any condition prevents calls tostd::call_once from executing as specified.
      • Any exception thrown byf.

      [edit]Notes

      If concurrent calls tostd::call_once pass different functionsf, it is unspecified whichf will be called. The selected function runs in the same thread as thestd::call_once invocation it was passed to.

      Initialization offunction-local statics is guaranteed to occur only once even when called from multiple threads, and may be more efficient than the equivalent code usingstd::call_once.

      The POSIX equivalent of this function ispthread_once.

      [edit]Example

      Run this code
      #include <iostream>#include <mutex>#include <thread> std::once_flag flag1, flag2; void simple_do_once(){    std::call_once(flag1,[](){std::cout<<"Simple example: called once\n";});} void may_throw_function(bool do_throw){if(do_throw){std::cout<<"Throw: call_once will retry\n";// this may appear more than oncethrowstd::exception();}std::cout<<"Did not throw, call_once will not attempt again\n";// guaranteed once} void do_once(bool do_throw){try{        std::call_once(flag2, may_throw_function, do_throw);}catch(...){}} int main(){std::thread st1(simple_do_once);std::thread st2(simple_do_once);std::thread st3(simple_do_once);std::thread st4(simple_do_once);    st1.join();    st2.join();    st3.join();    st4.join(); std::thread t1(do_once,true);std::thread t2(do_once,true);std::thread t3(do_once,false);std::thread t4(do_once,true);    t1.join();    t2.join();    t3.join();    t4.join();}

      Possible output:

      Simple example: called onceThrow: call_once will retryThrow: call_once will retryThrow: call_once will retryDid not throw, call_once will not attempt again

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      LWG 2080C++11std::invalid_argument would be thrown iff is invalid,
      but the scenario wheref is invalidated is not specified
      removed this error condition
      LWG 2442C++11the arguments were copied and/or moved before invocationno copying/moving is performed

      [edit]See also

      (C++11)
      helper object to ensure thatcall_once invokes the function only once
      (class)[edit]
      C documentation forcall_once
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/call_once&oldid=161108"

      [8]ページ先頭

      ©2009-2025 Movatter.jp