Maxbad`Blog

C++11 std::call_once:多线程仅执行一次的完美解决方案

2020-05-12 · 2 min read

std::call_once 的作用是很简单的,就是保证函数或者一些代码段在并发或者多线程的情况下,始终只会被执行一次。比如一些初始化函数,多次调用可能导致各种奇怪问题。
需要包含头文件:#include <mutex>

    template <class Fn, class... Args>
    void call_once(once_flag & flag, Fn && fn, Args &&...args);

参数

  • flag 是std::once_falg对象,属于控制的标签,相同的falg只执行一次
  • fn 需要只执行一次的函数对象
  • args 传递给fn函数的参数,如果有就传递,没有就不传递。

给个例子:

#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();
}

只会输出一行:Simple example: called once