c++11 call_once & once_flag

#include <iostream>
#include <mutex>
using namespace std;

void once_fun(std::once_flag &&flag)
{
    std::call_once(flag, []()
                   { cout << "message from once fun" << endl; });
}

void once_fun1(std::once_flag *flag)
{
    std::call_once(*flag, []()
                   { cout << "message from once fun 1" << endl; });
}

int foo(const char *msg)
{
    cout << "message from foo: " << msg << endl;
    return 123;
}

void CallOnceTest()
{
    std::once_flag flag;
    once_fun(std::move(flag)); // message from once fun
    once_fun(std::move(flag)); // no output

    std::once_flag flag1;
    once_fun1(&flag1); // message from once fun 1
    once_fun1(&flag1); // no output

    std::once_flag flag2;
    std::call_once(flag2, foo, "abc"); // message from foo: abc
    std::call_once(flag2, foo, "efg"); // no output
}
posted @ 2023-07-31 20:31  BuzzWeek  阅读(6)  评论(0编辑  收藏  举报