基于多线程的单例模式
- 当一个单例被多个线程获取的时候,如果不做相关的处理,可能导致,单例被重复创建,导致出现不可知的问题。
- 我们在获取单例的时候,对单例是否flag创建进行判断,当单例创建了,则直接返回单例。没有创建的时候,加了一个锁,先创建,并把flag置位true。返回创建的单例模式即可。
- 代码如下:
- #include
#include
#include
#include
using namespace std;
class Test
{
public:
static Test *getInstance()
{
if (ins_flag == true)
{
cout << “It been builded;” << endl;
return instance_;
}
else
{
std::unique_lockstd::mutex lock(mtx_);
if (nullptr == instance_)
{
instance_ = new Test();
ins_flag = true;
}
return instance_;
}
}
private:
Test()
{
cout << “this is a construction” << endl;
}
static std::mutex mtx_;
static Test *instance_;
static bool ins_flag;
};
bool Test::ins_flag = false;
Test* Test::instance_ = nullptr;
std::mutex Test::mtx_;//mutex变量在这放一下就行了。
void getInstance()
{
auto instance = Test::getInstance();
}
int main()
{
auto func = std::bind(getInstance);
std::thread th1[20];
for (int i = 0; i < 20; i++)
{
th1[i] = thread(func);
}
for (int i = 0; i < 20; i++)
{
th1[i].join();
}
system(“pause”);
return 0;
}
执行结果:
只执行了一次构造函数。