lundi 18 septembre 2017

How to access Singleton class member functions using different threads?

I am trying to run print() and print(char ch) methods on different threads with singleton instance .

Can any body help me out why I am getting errors:-

error C3867: 'Singleton::print': function call missing argument list; use '&Singleton::print' to create a pointer to member

error C3867: 'Singleton::print': function call missing argument list; use '&Singleton::print' to create a pointer to member

error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments

Also help me in correcting out the following code for me.


class Singleton
{
private:
    Singleton()
    {}
    static Singleton* singletonInstance;
public:
    static Singleton* getSingletonInstance();
    void print()
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        for (int i = 0; i < 100000; i++)
        {
            cout<<i<<endl;
        }
    }
    void print(char ch)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        for (int i = 0; i < 100000; i++)
        {
            cout<<ch<<" "<<i<<endl;
        }
    }
};
Singleton* Singleton::singletonInstance = nullptr;
Singleton* Singleton::getSingletonInstance()
{
    if(!singletonInstance)
        singletonInstance=new Singleton();

    return singletonInstance;
}

int main()
{
    std::thread t1(Singleton::getSingletonInstance()->print);
    std::thread t2(Singleton::getSingletonInstance()->print,'T');
    t1.join();
    t2.join();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire