推荐使用局部静态变量实现线程安全单例,C++11保证其初始化线程安全,代码简洁高效;也可用std::call_once控制初始化时机,或DCLP加std::atomic优化性能,但前者最常用且安全。

在C++中实现线程安全的单例模式,关键在于确保多个线程同时调用单例的获取实例方法时,只创建一个对象且不会发生竞争条件。现代C++(C++11及以上)提供了更简洁、安全的方式来实现这一点。
代码示例如下:
class Singleton {
public:
// 获取单例实例
static Singleton& getInstance() {
static Singleton instance; // 局部静态变量,自动线程安全
return instance;
}
<pre class='brush:php;toolbar:false;'>// 删除拷贝构造和赋值操作
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;private: // 构造函数私有 Singleton() = default; ~Singleton() = default; };
优点:简洁、高效、无需手动加锁,编译器保证首次初始化时的线程安全。
如果你需要更精细地控制初始化时机,可以使用 std::call_once 和 std::once_flag,它们能确保某段代码只执行一次,即使在多线程环境下。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <mutex>
<p>class Singleton {
public:
static Singleton& getInstance() {
static std::once_flag flag;
std::call_once(flag, [&]() {
instance.reset(new Singleton);
});
return *instance;
}</p><pre class='brush:php;toolbar:false;'>Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;private: Singleton() = default; ~Singleton() = default;
<pre class="brush:php;toolbar:false;">static std::unique_ptr<Singleton> instance;
};
// 静态成员定义 std::unique_ptr<Singleton> Singleton::instance = nullptr;
适用场景:当你想延迟初始化或配合智能指针管理生命周期时比较有用。
在老版本C++中常用双重检查锁定模式,但在C++11之后需结合 std::atomic 避免重排序问题。
示例:
#include <mutex>
#include <atomic>
<p>class Singleton {
public:
static Singleton<em> getInstance() {
Singleton</em> tmp = instance.load();
if (tmp == nullptr) {
std::lock<em>guard<std::mutex> lock(mutex</em>);
tmp = instance.load();
if (tmp == nullptr) {
tmp = new Singleton();
instance.store(tmp);
}
}
return tmp;
}</p><pre class='brush:php;toolbar:false;'>Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;private: Singleton() = default; ~Singleton() = default;
<pre class="brush:php;toolbar:false;">static std::atomic<Singleton*> instance; static std::mutex mutex_;
};
// 静态成员定义 std::atomic<Singleton*> Singleton::instance{nullptr}; std::mutex Singleton::mutex_;
注意:这种方式容易出错,不推荐新手使用,除非有特殊性能要求。
对于绝大多数现代C++项目,推荐使用局部静态变量的方式。它写法简单,编译器自动处理线程安全,且支持 RAII 和自动析构。
基本上就这些。不复杂但容易忽略细节,尤其是构造函数私有化和禁用拷贝。
以上就是c++++怎么写一个线程安全的单例模式_c++线程安全单例模式实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号