锁优化

This commit is contained in:
2026-07-23 12:27:07 +08:00
parent a8ea3cf8cb
commit bdb9f6c86b
+2 -23
View File
@@ -1,37 +1,16 @@
#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; // 若为 nullptrdelete 安全
static Derived instance;
return &instance;
}
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_;
}