Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      call_once, once_flag, ONCE_FLAG_INIT

      From cppreference.com
      <c‎ |thread
       
       
      Concurrency support library
       
      Defined in header<threads.h>
      void call_once(once_flag* flag,void(*func)(void));
      (1)(since C11)
      typedef/* unspecified */once_flag
      (2)(since C11)
      #define ONCE_FLAG_INIT /* unspecified */
      (3)(since C11)
      1) Calls functionfunc exactly once, even if invoked from several threads. The completion of the functionfunc synchronizes with all previous or subsequent calls tocall_once with the sameflag variable.
      2) Complete object type capable of holding a flag used bycall_once.
      3) Expands to a value that can be used to initialize an object of typeonce_flag.

      Contents

      [edit]Parameters

      flag - pointer to an object of typecall_once that is used to ensurefunc is called only once
      func - the function to execute only once

      [edit]Return value

      (none)

      [edit]Notes

      The POSIX equivalent of this function ispthread_once.

      [edit]Example

      Run this code
      #include <stdio.h>#include <threads.h> void do_once(void){puts("called once");} staticonce_flag flag=ONCE_FLAG_INIT;int func(void* data){    call_once(&flag, do_once);} int main(void){thrd_t t1, t2, t3, t4;thrd_create(&t1, func,NULL);thrd_create(&t2, func,NULL);thrd_create(&t3, func,NULL);thrd_create(&t4, func,NULL); thrd_join(t1,NULL);thrd_join(t2,NULL);thrd_join(t3,NULL);thrd_join(t4,NULL);}

      Output:

      called once

      [edit]References

      • C17 standard (ISO/IEC 9899:2018):
      • 7.26.2.1 The call_once function (p: 275)
      • 7.26.1/3 ONCE_FLAG_INIT (p: 274)
      • C11 standard (ISO/IEC 9899:2011):
      • 7.26.2.1 The call_once function (p: 378)
      • 7.26.1/3 ONCE_FLAG_INIT (p: 376)

      [edit]See also

      C++ documentation forcall_once
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/thread/call_once&oldid=136991"

      [8]ページ先頭

      ©2009-2025 Movatter.jp