支持并发的单例模式
单例模式是一个常用的编程范例,当我们希望程序中的某个实例最多只存在一个时,可以使用单例模式,下面是一个支持并发的单例模式的cpp代码示例:
#include <mutex>
class Singleton {
private:
inline static Singleton* instance = nullptr;
inline static std::mutex latch;
Singleton() {
// std::cout << " Singleton instance created." << std::endl;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
static Singleton* getInstance() {
std::scoped_lock<std::mutex> lock{latch};
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
void doSomething() {
// std::cout << "Doing something." << std::endl;
}
static void releaseInstance() {
if (instance != nullptr) {
delete instance;
instance = nullptr;
// std::cout << " Singleton instance destroyed." << std::endl;
}
}
};