Namespaces
Variants

call_once, once_flag, ONCE_FLAG_INIT

From cppreference.net
Definiert im Header <threads.h>
void call_once ( once_flag * flag, void ( * func ) ( void ) ) ;
(1) (seit C11)
typedef /* unspecified */ once_flag
(2) (seit C11)
#define ONCE_FLAG_INIT /* unspecified */
(3) (seit C11)
1) Ruft die Funktion func genau einmal auf, selbst wenn sie von mehreren Threads aufgerufen wird. Der Abschluss der Funktion func synchronisiert mit allen vorherigen oder nachfolgenden Aufrufen von call_once mit derselben flag Variable.
2) Vollständiger Objekttyp, der in der Lage ist, eine von call_once verwendete Flagge zu halten.
3) Erweitert sich zu einem Wert, der zur Initialisierung eines Objekts vom Typ once_flag verwendet werden kann.

Inhaltsverzeichnis

Parameter

flag - Zeiger auf ein Objekt vom Typ call_once , das verwendet wird, um sicherzustellen, dass func nur einmal aufgerufen wird
func - die Funktion, die nur einmal ausgeführt werden soll

Rückgabewert

(keine)

Hinweise

Das POSIX-Äquivalent dieser Funktion ist pthread_once .

Beispiel

#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);
}

Ausgabe:

called once

Referenzen

  • C17-Standard (ISO/IEC 9899:2018):
  • 7.26.2.1 Die call_once-Funktion (S: 275)
  • 7.26.1/3 ONCE_FLAG_INIT (S: 274)
  • C11-Standard (ISO/IEC 9899:2011):
  • 7.26.2.1 Die call_once-Funktion (S: 378)
  • 7.26.1/3 ONCE_FLAG_INIT (S: 376)

Siehe auch

C++-Dokumentation für call_once