template <class Fn, class... Args>

        void call_once (once_flag& flag, Fn&& fn, Args&&...args);

Need to include header file :<mutex>

parameter :

(1)flag: yes std::once_falg object ( Define an object and pass it in ),, Label belonging to control , same falg Only once ( See details below )

(2)fn: Function objects that need to be executed only once ,,

(3)args: Pass to fn The parameters of the function ,, Pass it on if you have one , No, no delivery .

The following is explained through the procedure flag The role of :

#include<iostream> #include<mutex> #include<thread> using namespace std; void
init() { cout << "data has inited" << endl; } void fun() { once_flag init_flag;
// Wrong usage call_once(init_flag, init); } int main() { thread t1(fun); thread
t2(fun); t1.join(); t2.join(); system("pause"); return 0; } Operation results :

You can see the output twice “data has
inited”, that is because init_flag Is defined in fun Local variables in , Per thread fun In function init_flag It's different , All will be output twice ,, If init_flag It's a global variable, etc , It's the same variable , It will only output once ., The same as above flag Only once . It should be understood .

Correct demonstration of the above program after modification :

#include<iostream> #include<mutex> #include<thread> using namespace std;
once_flag init_flag; void init() { cout << "data has inited" << endl; } void
fun() { call_once(init_flag, init); } int main() { thread t1(fun); thread
t2(fun); t1.join(); t2.join(); system("pause"); return 0; } Operation results :

This time it's only output once ,, The description was executed only once !

purpose :

std::call_once It is mainly used for the scenario of multi-threaded resource initialization only once , The typical example is the perfect solution to thread safety single column mode .

Technology