Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and why use call_once()?

Tags:

c

c23

From N3220, §7.28.2.1 “The call_once function”:

Synopsis

#include <threads.h>
void call_once(once_flag *flag, void (*func)(void));

Description

The call_once function uses the once_flag pointed to by flag to ensure that func is called exactly once, the first time the call_once function is called with that value of flag. Completion of an effective call to the call_once function synchronizes with all subsequent calls to the call_once function with the same value of flag.

Returns

The call_once function returns no value.

From what it sounds like, is this supposed to be used for init()/config() functions that are only supposed to be called once? Or am I completely misunderstanding it and it is something pertinent to threads?

What is this useful for? What is flag, and how is it relevant here?

like image 269
Madagascar Avatar asked Feb 04 '26 15:02

Madagascar


1 Answers

Let's assume the following:

  • The same function is provided for all calls with a given flag object.
  • The same flag object is provided for all calls with a given function.
  • The function is only called via call_once.

If those assumptions are met, the following two guarantees are made for any function provided as an argument:

  • The function will be called only once.
  • call_once will only return once the function has returned.

The second guarantee means that other threads will block until the provided function returns if it's currently executing.

This is useful for initializing/populating shared variables.

like image 83
ikegami Avatar answered Feb 06 '26 11:02

ikegami