call_once
在头文件<threads.h>中定义 | | |
---|---|---|
void call_once(once_flag * flag,void(* func)(void)); | (1) | (自C11以来) |
typedef / *未指定* / once_flag | (2) | (自C11以来) |
#define ONCE_FLAG_INIT / *未指定* / | (3) | (自C11以来) |
1)即使从多个线程调用,也只调用一次函数func。 函数func的完成与所有之前或之后对具有相同标志变量的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
参考
- C11标准(ISO / IEC 9899:2011):
- 7.26.2.1 call_once函数(p:378)
- 7.26.1 / 3 ONCE_FLAG_INIT(p:376)
扩展内容
| call_once的C ++文档 |
|:----|
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com