The std::call_once
function, introduced in C++11, ensures a callable is called exactly one time, in a thread safe manner.
Since this can be achieved by other means - when should std::call_once
be used? What type of problems is it intended to address?
Please provide examples.
std::call_once ensures execution of a function exactly once by competing threads. It throws std::system_error in case it cannot complete its task.
The CPP Reference states std::call_once is thread safe: Executes the function f exactly once, even if called from several threads.
Example: I use it for libcURL to retrieve http(s) data from websites. In libcURL, you have to do a one-time global initialization before you're able to use the library. Given that initialization is not thread-safe, but requesting data from websites is thread-safe, I use call_once
that calls my initialization only once, no matter in what thread and whether it's called concurrently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With