C++中的 std::call_once()

一、简介

多线程并发只执行一次。

 

二、实验

#include <iostream>
#include <thread>
#include <mutex>

//用法1:
std::once_flag o_flag;
void init_func()
{
    std::cout << "after init!" << std::endl;
}
void thread_func()
{
    std::call_once(o_flag, init_func);
}

//用法2:
void test_func()
{
    int a = 11, b = 33, c = 55;
    static std::once_flag slo_flag;

    std::call_once(slo_flag, [&](){ //所有局部变量都可以修改(默认全局变量可修改)
        a++;
        b++;
        c++;
        std::cout << "a=" << a << " " << "b=" << b << " " << "c=" << c << std::endl; //为啥没打印?
    });
}


int main()
{
    std::thread t1(thread_func);
    std::thread t2(thread_func);

    std::thread t3(test_func);
    std::thread t4(test_func);

    t1.join();
    t2.join();
    t3.join();
    t4.join();
 
    return 0;
}

/*
$ g++ call_once_test.cpp -o pp -lpthread
$ ./pp
after init!
a=12 b=34 c=56
*/

 

三、补充

1. ProcessState.cpp 中有对 std::call_once() 的使用,栈回溯上可以看到其内部调用函数签名是:std::__1::__call_once(unsigned long volatile&, void*, void (*)(void*))

 

posted on 2025-11-04 11:01  Hello-World3  阅读(3)  评论(0)    收藏  举报

导航