vendredi 21 septembre 2018

Singleton class not working as expected C++

I am working on a project that involves creating a singleton class.. So I have created a shared library for the singleton class and created two binaries to use this class. When the first exe calls the class's static function "getInstance()" a new instance of Singleton is created and this is expected but when i call getInstance() from the second exe a new instance of Singleton is created again ideally it should have returned the instance created in first case. Here is he code

singelton.h :

#include <iostream>
#include <stdio.h>

using namespace std;

class Singleton
{
private:
    static Singleton *single;
    Singleton()
    {
        //private constructor
    }
public:
    static Singleton* getInstance();
    void method();
    ~Singleton()
    {
    }
};

singleton.cpp

#include "singleton.h"

Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
    if(single == NULL)
    {
        printf("Creating a new instance of singleton\n");
        single = new Singleton();
        return single;
    }
    else
    {
        return single;
    }
}

void Singleton::method()
{
    cout << "Method of the singleton class" << endl;
}

main_test1.cpp :

#include "singleton.h"

int main()
{
    printf("entering test1\n");
    Singleton* singleton = Singleton::getInstance();

    if(singleton != NULL)
    {
        singleton->method();
    }

    while(1)
    {
        sleep(60);
    }
}

main_test2.cpp :

#include "singleton.h"

int main()
{
    printf("entering test2\n");
    Singleton* singleton = Singleton::getInstance();

    if(singleton != NULL)
    {
        singleton->method();
    }
}

Makefile :

DEPS = singleton.h
CC = gcc

shared :  $(DEPS)
    $(CC) -o libsingleton.so singleton.cpp -fPIC -shared

test1 : main_test1.o libsingleton.so
    $(CC) -o test1 main_test1.o libsingleton.so -lstdc++ -rdynamic

test2 : main_test2.o libsingleton.so
    $(CC) -o test2 main_test2.o libsingleton.so -lstdc++ -rdynamic

clean : 
    rm *.o test2 test1 libsingleton.so

.PHONY : clean

Expected result :

$./test1&
$ entering test1
Creating a new instance of singleton
Method of the singleton class

$ ./test2
entering test2
Method of the singleton class

Current result :

$./test1&
$ entering test1
Creating a new instance of singleton
Method of the singleton class

$ ./test2
entering test2
Creating a new instance of singleton
Method of the singleton class

Aucun commentaire:

Enregistrer un commentaire