锁优化
This commit is contained in:
@@ -1,37 +1,16 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <mutex>
|
|
||||||
#include <atomic>
|
|
||||||
namespace Psc {
|
namespace Psc {
|
||||||
template<typename Derived>
|
template<typename Derived>
|
||||||
class Singleton {
|
class Singleton {
|
||||||
public:
|
public:
|
||||||
static Derived *instance() {
|
static Derived *instance() {
|
||||||
Derived *temp = instance_.load(std::memory_order_acquire);
|
static Derived instance;
|
||||||
if (temp == nullptr) {
|
return &instance;
|
||||||
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(const Singleton &) = delete;
|
||||||
Singleton &operator=(const Singleton &) = delete;
|
Singleton &operator=(const Singleton &) = delete;
|
||||||
protected:
|
protected:
|
||||||
Singleton() = default;
|
Singleton() = default;
|
||||||
~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