call_once, once_flag, ONCE_FLAG_INIT
From cppreference.net
|
Definido en el encabezado
<threads.h>
|
||
|
void
call_once
(
once_flag
*
flag,
void
(
*
func
)
(
void
)
)
;
|
(1) | (desde C11) |
|
typedef
/* no especificado */
once_flag
|
(2) | (desde C11) |
|
#define ONCE_FLAG_INIT /* no especificado */
|
(3) | (desde C11) |
1)
Llama a la función
func
exactamente una vez, incluso si se invoca desde varios hilos. La finalización de la función
func
se sincroniza con todas las llamadas anteriores o posteriores a
call_once
con la misma variable
flag
.
2)
Tipo de objeto completo capaz de contener un indicador utilizado por
call_once
.
3)
Se expande a un valor que puede utilizarse para inicializar un objeto de tipo
once_flag
.
Contenidos |
Parámetros
| flag | - |
puntero a un objeto de tipo
call_once
que se utiliza para garantizar que
func
se llame solo una vez
|
| func | - | la función a ejecutar solo una vez |
Valor de retorno
(ninguno)
Notas
El equivalente POSIX de esta función es
pthread_once
.
Ejemplo
Ejecutar este código
#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); }
Salida:
called once
Referencias
- Estándar C17 (ISO/IEC 9899:2018):
-
- 7.26.2.1 La función call_once (p: 275)
-
- 7.26.1/3 ONCE_FLAG_INIT (p: 274)
- Estándar C11 (ISO/IEC 9899:2011):
-
- 7.26.2.1 La función call_once (p: 378)
-
- 7.26.1/3 ONCE_FLAG_INIT (p: 376)
Véase también
|
Documentación de C++
para
call_once
|