一、call_once 单例模式 Singleton
大家可以先看这篇文章:https://zh.cppreference.com/w/cpp/thread/call_once
/*
std::call_once
void call_once( std::once_flag& flag, Callable&& f, Args&&... args );
*/
#include <iostream>
#include <mutex>
#include <thread>
std::once_flag flag1, flag2;
void simple_do_once() {
std::call_once(flag1, []() {
std::cout << "简单样例:调用一次\n";
});
}
void test1() {
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();
}
void may_throw_function(bool do_throw) {
if (do_throw) {
std::cout << "抛出:call_once 会重试\n"; // 这会出现不止一次
throw std::exception();
}
std::cout << "没有抛出,call_once 不会再重试\n"; // 保证一次
}
void do_once(bool do_throw) {
try {
std::call_once(flag2, may_throw_function, do_throw);
}
catch (...) {}
}
void test2() {
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();
}
int main() {
test1();
test2();
return 0;
}
call_once 应用在单例模式,以及关于单例模式我的往期文章推荐:C++ 设计模式----“对象性能“模式_爱编程的大丙 设计模式-CSDN博客https://heheda.blog.csdn.net/article/details/131466271
懒汉是一开始不会实例化,什么时候用就什么时候new,才会实例化
饿汉在一开始类加载的时候就已经实例化,并且创建单例对象,以后只管用即可
--来自百度文库