江门网站制作模板,广东网站建设多少钱,长春做网站好的公司,电子商务工作室经营范围双重检查锁定#xff08;也称为“双重检查锁定优化”#xff09;是一种用于减少获取锁的开销的软件设计模式。它通过在获取锁之前测试锁定条件#xff08;即“锁提示”#xff09;来实现。只有在锁定条件检查表明需要锁定时才会进行锁定操作。
#include atomic
#i…双重检查锁定也称为“双重检查锁定优化”是一种用于减少获取锁的开销的软件设计模式。它通过在获取锁之前测试锁定条件即“锁提示”来实现。只有在锁定条件检查表明需要锁定时才会进行锁定操作。
#include atomic
#include mutexclass Singleton {public:static Singleton* GetInstance();private:Singleton() default;static std::atomicSingleton* s_instance;static std::mutex s_mutex;
};Singleton* Singleton::GetInstance() {Singleton* p s_instance.load(std::memory_order_acquire); // Aif (p nullptr) { // 1st checkstd::lock_guardstd::mutex lock(s_mutex);p s_instance.load(std::memory_order_relaxed);if (p nullptr) { // 2nd (double) checkp new Singleton();s_instance.store(p, std::memory_order_release); // B}}return p;
}memory_order_acquire主要保证两个事情
相同原子变量的release操作此处可见创建一个同步synchronization边界任何读写都不会被重排到该操作之前
memory_order_release主要保证两个事情
内存写操作对acquire相同原子变量的线程可见创建一个同步synchronization边界任何读写都不会被重排到该操作之后
即假设A、B两个线程同时运行于A、B点B的release操作对线程A可见。同时p new Singleton()的读写操作不会被重排到B点之后。
C 11提供了基于该范式实现的基础设施std::once_flag和std::call_once:
#include mutex
#include optional // Since C17// Singleton.h
class Singleton {public:static Singleton* GetInstance();private:Singleton() default;static std::optionalSingleton s_instance;static std::once_flag s_flag;
};// Singleton.cpp
std::optionalSingleton Singleton::s_instance;
std::once_flag Singleton::s_flag{};Singleton* Singleton::GetInstance() {std::call_once(Singleton::s_flag,[]() { s_instance.emplace(Singleton{}); });return *s_instance;
}