jeudi 3 janvier 2019

How to prevent multiple threads to use singleton class instance at same time in cpp

I am writting a thread safe singleton class as follows. The following implementation ensures that only one instance of the class in created. My use case is that I am using this instance in a multi thread environment where each thread may call getInstance() and do some work using the instance. My question is how can I ensure that only one thread is using the instance at a particular time, so as to prevent race conditions that might occur if multiple threads are trying to use the single instance at same time.

class Singleton {
    Singleton() {}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
 public:
    static Singleton& getInstance() {
        static Singleton s;
        return s;
    }
};

Aucun commentaire:

Enregistrer un commentaire