C++ (Qt) multi-threaded singleton mode double detection realization

Seeing Singleton, anyone who has studied design patterns knows that it is the singleton mode, which means that there is only one instance of a certain variable when the program is executed.

class Singleton {
public:
     static Singleton * getInstance() {}
private:
     Singleton(): {}
     ~Singleton(): {}
     static Singleton * instance;
}
 
Singleton * Singleton::instance = nullptr;
 
Singleton * Singleton::getInstance(){
    if(!instance){
        instance = new Singleton;    //pos
    }
    return instance; 
}

The above code is only for single thread, because if there are multiple threads calling getInstance, maybe one thread has just reached the position of pos, and the second thread is doing the if judgment, then its judgment will also be established, because the instance does not The assignment is successful.

If multi-threaded implementation is required, it should be applied to locks, similar to process pv operations, to ensure that only one process accesses critical resources at the same time. So getInstance() can be changed to

Singleton*Singleton::getInstance()
{
    static QMutex mutex;
    if(!instance)
    {
        QMutexLocker locker(&mutex);
        if(!instance)
        {
            instance = new Singleton;
        }
    }
    return instance;
}

 

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/112831234