1. 程式人生 > >一種多執行緒安全的單例模式

一種多執行緒安全的單例模式

template <typename T>
class StaticSingletonT {
public:
static T* SafeInstance() {
    static T* s_instance_ptr = NULL;
    if (!s_instance_ptr) {
        if (atomic_compare_exchange(&s_state, 
            OBJECT_CREATING, 
            OBJECT_NOT_CREATE) == OBJECT_NOT_CREATE) {
                s_instance_ptr = StaticSingletonT<T>::GetInstance();
                s_state = OBJECT_CREATED;
        } else {
            while (s_state != OBJECT_CREATED) usleep(1);
            s_instance_ptr = StaticSingletonT<T>::GetInstance();
        }
    }
    return s_instance_ptr;
}

private:
    static T* GetInstance() { static T s_instance; return &s_instance; }

private:
    enum OBJECT_STATE {
        OBJECT_NOT_CREATE = 0,              // Not created
        OBJECT_CREATING   = 1,              // Creating
        OBJECT_CREATED    = 2               // Has been created
    };
    static volatile uint32_t s_state;
};
template<class T> volatile uint32_t StaticSingletonT<T>::s_state = OBJECT_NOT_CREATE;
ps:atomic_compare_exchange換成對應平臺支援的API