3

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?

5
  • en.cppreference.com/w/c/thread/call_once shows usage example
    – KamilCuk
    Commented Jun 6 at 19:37
  • @KamilCuk "The completion of the function func synchronizes with all previous or subsequent calls to call_once with the same flag variable." <== What does this mean?
    – Harith
    Commented Jun 6 at 19:38
  • 3
    Which part is unclear to you?
    – KamilCuk
    Commented Jun 6 at 19:39
  • @KamilCuk Well, everything after "function func". I am not very familiar with threads. :(
    – Harith
    Commented Jun 6 at 19:39
  • 3
    @Closevoter 1) How in the world am I seeking recommendations for software tools and libraries? I am asking about the usage of a function. Questions asking about scanf() and printf() don't get closed for seeking recommendations for software tools. 2. I do not see any duplicate about call_once().
    – Harith
    Commented Jun 6 at 19:41

1 Answer 1

3

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.