Tower of Hanoi
Tower of Hanoi
June 13, 2023
Viewpoints in testing
Viewpoints in testing
June 27, 2023

June 20, 2023

Double Checked Locking Pattern

Double checked locking pattern was used in sigleton initialization in multi-threaded environments prior to C++11.

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load(std::memory_order_acquire);
    if (tmp == nullptr) {
        std::lock_guard lock(m_mutex);
        tmp = m_instance.load(std::memory_order_relaxed);
        if (tmp == nullptr) {
            tmp = new Singleton;
            m_instance.store(tmp, std::memory_order_release);
        }
    }
    return tmp;
}

C++11 removes the need for manual locking. It guarantees concurrent execution shall wait if a static local variable is already being initialized. You can simply use a static initializer.

Singleton& Singleton::getInstance() {
    static Singleton instance;
    return instance;
}
Double Checked Locking Pattern
This website uses cookies to improve your experience. By using this website you agree to our Data Privacy Statement
Read more