std::call_once的作用是很簡單的, 就是保證函數或者一些代碼段在並發或者多線程的情況下,始終只會被執行一次。比如一些init函數,多次調用可能導致各種奇怪問題。
給個例子:
#include <iostream> #include <thread> #include <mutex> std::once_flag flag1; void simple_do_once() { std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; }); } int main() { std::thread st1(simple_do_once); std::thread st2(simple_do_once); std::thread st3(simple_do_once); std::thread st4(simple_do_once); st1.join(); st2.join(); st3.join(); st4.join(); }
Output:
Simple example: called once
