call_once
std::call_once(参数一,参数二(函数接口))的功能是保证一个函数只被调用一次,此方法具有互斥量的能力,并且消耗比互斥量少。此函数需要与标记std::once_flag配合使用,通过该标记决定函数是否调用,如果调用成功后,标记被设置为已调用状态。
作用:防止在多个线程中存在创建多个单例对象产生的重复创建情况
#include <iostream>
#include <mutex>
using namespace std;
once_flag flag;
class A
{
public:
static void CreateInstance()
{
m_inc = new A();
static CGbruidstr cg;
}
static A* Instance()
{
call_once(flag, CreateInstance);
return m_inc;
}
class CGbruidstr
{
public:
~CGbruidstr()
{
if (A::m_inc)
{
delete A::m_inc;
m_inc = nullptr;
}
}
};
void func()
{
cout << "测试" << endl;
}
private:
A() {};
static A *m_inc;
};
A* A::m_inc = nullptr;
int main() {
cout << "main thread" << endl;
return 0;
}