Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::call_once, when should it be used?

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.

like image 624
darune Avatar asked Apr 03 '19 08:04

darune


People also ask

What is std :: Call_once?

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.

Is std :: Call_once thread safe?

The CPP Reference states std::call_once is thread safe: Executes the function f exactly once, even if called from several threads.


1 Answers

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.

like image 176
The Quantum Physicist Avatar answered Oct 05 '22 09:10

The Quantum Physicist