#include <iostream>
#include <mutex>
#include <pthread.h>
constexpr auto times = 50;
class MySingleton
{
public:
static MySingleton &getInstance()
{
std::call_once(initInstanceFlag, &MySingleton::initSingleton);
volatile int dummy{};
return *instance;
}
private:
MySingleton() = default;
~MySingleton() = default;
MySingleton(const MySingleton &) = delete;
MySingleton &operator=(const MySingleton &) = delete;
static MySingleton *instance;
static std::once_flag initInstanceFlag;
static void initSingleton()
{
instance = new MySingleton;
}
};
MySingleton *MySingleton::instance = nullptr;
std::once_flag MySingleton::initInstanceFlag;
int main()
{
for (size_t i = 0; i <= times; ++i)
{
std::cout<<&MySingleton::getInstance()<<std::endl;
}
system("pause");
return 0;
}
g++ -o test test.cpp -pthread
xz@xiaqiu:~/study/test/test$ ./test
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
0x563298806eb0
sh: 1: pause: not found
xz@xiaqiu:~/study/test/test$
|