C++11 call_once和once_flag

call_once是c++11中引入的新特性,用于保证某个函数只调用一次,即使是多线程环境下,它也可以可靠地完成一次函数调用。一般配合once_flag变量。

特别适用于多线程时某个初始化只执行一次的场景。

  • 若调用call_once一切顺利,将会翻转once_flag变量的内部状态,再次调用该函数时,所对应的目标函数不会被执行。
  • 若调用call_once中发生异常,不会翻转once_flag变量的内部状态,再次调用该函数时,目标函数仍然尝试执行。
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono> 
#include <thread>
using namespace std::chrono_literals;
std::once_flag flag1, flag2;

void simple_do_once() {
    std::this_thread::sleep_for(2s);
    std::call_once(flag1, []() { std::cout << "Simple example: called once\n"; });
}

void may_throw_function(bool do_throw) {
    std::this_thread::sleep_for(2s);

    if (do_throw) {
        std::cout << "throw: call_once will retry\n"; // this may appear more than once
        throw std::exception();
    }
    std::cout << "Didn't throw, call_once will not attempt again" << std::endl; // guaranteed once
}

void do_once(bool do_throw) {
    try {
        std::call_once(flag2, may_throw_function, do_throw);
    } catch (...) {
    }
}

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

    std::thread t1(do_once, true);
    std::thread t2(do_once, true);
    std::thread t3(do_once, false);
    std::thread t4(do_once, true);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}
posted @ 2022-05-06 10:40  天下太平  阅读(175)  评论(0编辑  收藏  举报