当前位置: 首页 > news >正文

C++中的 std::call_once() - Hello

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
*/