#include<iostream>
#include<string>
#include<thread>
#include<chrono>
using namespace std;
class Singleton{
private:
string m_str;
Singleton(const string& s) : m_str(s) { }
static Singleton* p_singleton;
public:
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
static Singleton* instance(const string& s)
{
if(p_singleton == nullptr){
p_singleton = new Singleton(s);
}
return p_singleton;
}
string value()const
{
return m_str;
}
};
Singleton* Singleton::p_singleton = nullptr;
void threadFoo()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::instance("foo");
cout << singleton->value() << endl;
}
void threadBar()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
Singleton* singleton = Singleton::instance("bar");
cout << singleton->value() << endl;
}
int main()
{
threadBar();
threadFoo();
return 0;
}