文章目录
- call_once
- 示例一
- 示例二
call_once
std::call_once
是 C++11 标准库中的一个函数,用于确保某个函数只会被调用一次。
单例设计模式是一种常见的设计模式,用于确保某个类只能创建一个实例。由于单例实例是全局唯一的,因此在多线程环境中使用单例模式时,需要考虑线程安全的问题。
下面是一个简单的单例模式的实现:
示例一
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
using namespace std;
static once_flag m_onceFlag;
class Log {
public:static Log* getInstance(){call_once(m_onceFlag, init);//保证有一个对象cout << &m_instance << endl;return m_instance;}static void init(){if (m_instance == nullptr){m_instance = new Log;}}void printStr(string str){cout <<__TIME__ <<"::"<<str << endl;}static Log* m_instance;
};
Log* Log::m_instance = nullptr;
void print_thread(string str)
{Log::getInstance()->printStr(str);
}
int main()
{thread t1(print_thread,"t1");thread t2(print_thread, "t2");t1.join();t2.join();while (1){}return 0;
}
示例二
#include <iostream>
using namespace std;
#include <thread>
#include <mutex>once_flag g_flag;void do_once(int a, string b) {cout << "name: " << b << ", age: " << a << endl;
}void do_something(int age, string name) {static int num = 1;call_once(g_flag, do_once, 19, "luffy");cout << "do_something() function num = " << num++ << endl;
}int main() {thread t1(do_something, 20, "ace");thread t2(do_something, 20, "sabo");thread t3(do_something, 20, "luffy");t1.join();t2.join();t3.join();return 0;
}
执行结果
name: luffy, age: 19
do_something() function num = 1
do_something() function num = 2
do_something() function num = 3
通过输出的结果可以看到,虽然运行的三个线程中都执行了任务函数do_something()但是call_once()中指定的回调函数只被执行了一次,我们的目的也达到了。