Initial commit
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
namespace Psc {
|
||||
template<typename Derived>
|
||||
class Singleton {
|
||||
public:
|
||||
static Derived *instance() {
|
||||
Derived *temp = instance_.load(std::memory_order_acquire);
|
||||
if (temp == nullptr) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
temp = instance_.load(std::memory_order_relaxed);
|
||||
if (temp == nullptr) {
|
||||
temp = new Derived;
|
||||
instance_.store(temp, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
static void destroy() {
|
||||
Derived* temp = instance_.exchange(nullptr, std::memory_order_acq_rel);
|
||||
delete temp; // 若为 nullptr,delete 安全
|
||||
}
|
||||
Singleton(const Singleton &) = delete;
|
||||
Singleton &operator=(const Singleton &) = delete;
|
||||
protected:
|
||||
Singleton() = default;
|
||||
~Singleton() = default;
|
||||
private:
|
||||
static std::atomic<Derived *> instance_;
|
||||
static std::mutex mutex_;
|
||||
};
|
||||
template<typename Derived>
|
||||
std::atomic<Derived *> Singleton<Derived>::instance_(nullptr);
|
||||
template<typename Derived>
|
||||
std::mutex Singleton<Derived>::mutex_;
|
||||
}
|
||||
Reference in New Issue
Block a user