#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
class singleton
{
private:
static int count;
static singleton *instance; // this instace is created as static as it will crete only once and all the objects
// which are created will use only this instance
static mutex m;
singleton() //default constrcutor// these all are kept in private to avoid creation of objects
{
count++;
cout<<"Instance has been created : "<<count<<" time"<<endl;
}
singleton(const singleton &s); //copy constructor to keep in private in oder to avoid copying the object as it can create as default
singleton operator=(const singleton &s); //similar with the assignment operator
public:
void print(string msg)
{
cout<<msg<<endl;
}
static singleton* getinstance() // this is static member fuction created to access the static data members and return the instace
{
if(instance == nullptr)
{
m.lock();
if(instance == nullptr)
{
instance = new singleton();
}
m.unlock();
}
return instance;
}
};
int singleton::count =0;
singleton* singleton::instance=nullptr;
mutex singleton::m;
void funcinst1()
{
singleton *s1 = singleton::getinstance();
s1->print("s1 instance is created");
}
void funcinst2()
{
singleton *s2 = singleton::getinstance();
s2->print("s2 instance is created");
}
int main() {
thread t1(funcinst1);
thread t2(funcinst2);
t1.join();
t2.join();
}
To embed this project on your website, copy the following code and paste it into your website's HTML: