答案:c++中线程安全单例常用std::call_once和双重检查锁定,前者由标准库保障安全且简洁,后者需手动加锁并二次检查以防竞态,但易出错;推荐优先使用局部静态变量或std::call_once。

在C++中实现线程安全的单例模式,常用的方法有两种:使用 std::call_once 与 std::once_flag,以及经典的“双重检查锁定”(double-Checked Locking)模式。下面分别介绍这两种方式,并说明它们的优缺点和适用场景。
使用 std::call_once 保证线程安全
std::call_once 是 C++11 提供的一种机制,确保某个函数在整个程序生命周期中只被调用一次,即使在多线程环境下也是如此。配合 std::once_flag 使用,非常适合实现线程安全的单例。
示例代码:
#include <mutex> <p>class Singleton { public: Static Singleton& getInstance() { std::call_once(initInstanceFlag, &Singleton::init); return *instance; }</p><p>private: Singleton() = default; static void init() { instance = new Singleton(); }</p><pre class='brush:php;toolbar:false;'>static std::once_flag initInstanceFlag; static Singleton* instance;
};
立即学习“C++免费学习笔记(深入)”;
// 静态成员定义 std::once_flag Singleton::initInstanceFlag; Singleton* Singleton::instance = nullptr;
这种方式的优点是简洁、安全,由标准库保证初始化的唯一性和线程安全,开发者无需手动加锁或处理竞态条件。
双重检查锁定(Double-Checked Locking)
这种模式旨在减少加锁开销,在实例已创建后避免每次调用都进入临界区。其核心逻辑是:先判断指针是否为空,若为空再加锁,然后再次检查(防止多个线程同时通过第一次检查),最后创建实例。
示例代码:
#include <mutex> <p>class Singleton { public: static Singleton* getInstance() { if (instance == nullptr) { // 第一次检查 std::lock<em>guard<std::mutex> lock(mutex</em>); if (instance == nullptr) { // 第二次检查 instance = new Singleton(); } } return instance; }</p><p>private: Singleton() = default; static Singleton* instance; static std::mutex mutex_; };</p><p>// 静态成员定义 Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex_;
需要注意的是,虽然该模式常见,但在 C++ 中必须确保内存模型的安全性。在 C++11 及以后版本中,只要使用了 std::mutex 等同步原语,双重检查锁定是安全的。但若使用裸指针和 volatile 不当,可能因编译器重排序导致未完全构造的对象被其他线程访问。
对比与建议
- std::call_once 更推荐用于现代 C++ 项目,它语义清晰、不易出错,且性能开销极小(仅首次调用有同步成本)。
- 双重检查锁定 虽然高效,但实现稍复杂,容易因细节疏忽引入 bug,比如忘记第二次检查或使用了非原子操作。
- 如果单例对象可以接受局部静态变量的方式,还可以直接使用Meyers 单例:
static Singleton& getInstance() { static Singleton instance; return instance; }
在 C++11 之后,局部静态变量的初始化是线程安全的,这是最简洁安全的写法。
基本上就这些。对于大多数情况,优先选择局部静态变量或 std::call_once,避免手动管理锁和指针。不复杂但容易忽略细节。