命名空间
变体
操作

call_once, once_flag, ONCE_FLAG_INIT

来自 cppreference.cn
< c‎ | thread
在头文件 <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 - 指向 call_once 类型对象的指针,用于确保 func 只被调用一次
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

[编辑] 参考

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

[编辑] 另请参阅

C++ 文档 for call_once