call_once, once_flag, ONCE_FLAG_INIT
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    | 在标头  <threads.h>定义 | ||
| void call_once( once_flag* flag, void (*func)(void) ); | (1) | (C11 起) | 
| typedef /* unspecified */ once_flag | (2) | (C11 起) | 
| #define ONCE_FLAG_INIT /* unspecified */ | (3) | (C11 起) | 
1) 准确调用函数 
func 一次,即使从多个线程调用。函数 func 的完成与先前或后继的用同一 flag 对象的对 call_once 调用同步。2) 足以保有 
call_once 所用标志的完整对象类型。3) 展开成能用于初始化 
once_flag 类型对象的值。参数
| flag | - | 指向用于确保只调用一次 func的call_once对象的指针 | 
| func | - | 只执行一次的函数 | 
返回值
(无)
注意
此函数的 POSIX 等价物是 pthread_once 。
示例
运行此代码
#include <stdio.h> #include <threads.h> void do_once(void) { puts("called once"); } static once_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); }
输出:
called once
引用
- C11 标准(ISO/IEC 9899:2011):
- 7.26.2.1 The call_once function (第 378 页)
 
- 7.26.1/3 ONCE_FLAG_INIT (第 376 页)