当前位置: 首页 > news >正文

C++ `unique_ptr` 多线程使用

C++ unique_ptr 多线程使用


一、核心结论
  • 操作同一个 unique_ptr:必须加锁(所有权转移是非原子操作)
  • 访问被管理对象:若对象非线程安全,仍需额外同步
  • 独立 unique_ptr 实例:不同线程操作不同实例时无需加锁

二、错误案例(未加锁导致数据竞争)
#include <iostream>
#include <memory>
#include <thread>// 全局 unique_ptr(危险!)
std::unique_ptr<int> unsafe_ptr;void unsafe_thread() {// 多线程同时修改同一个 unique_ptrunsafe_ptr = std::make_unique<int>(42);
}int main() {std::thread t1(unsafe_thread);std::thread t2(unsafe_thread);t1.join();t2.join();if (unsafe_ptr) {std::cout << "危险操作结果: " << *unsafe_ptr << "\n";} else {std::cout << "指针已丢失\n"; // 可能输出}return 0;
}

可能输出(结果不确定):

指针已丢失
Segmentation fault (core dumped)  // 可能崩溃

三、正确实现(加锁保护所有权转移)
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>// 全局资源
std::unique_ptr<int> safe_ptr;
std::mutex ptr_mutex;void safe_writer(int val) {std::lock_guard<std::mutex> lock(ptr_mutex);safe_ptr = std::make_unique<int>(val);  // 安全修改
}void safe_reader() {std::unique_ptr<int> local_copy;{std::lock_guard<std::mutex> lock(ptr_mutex);if (safe_ptr) {local_copy = std::make_unique<int>(*safe_ptr);  // 安全拷贝值}}if (local_copy) {std::cout << "安全读取: " << *local_copy << "\n";}
}int main() {std::thread writers[2];std::thread readers[2];// 启动写入线程for (int i = 0; i < 2; ++i) {writers[i] = std::thread(safe_writer, i * 100);}// 启动读取线程for (int i = 0; i < 2; ++i) {readers[i] = std::thread(safe_reader);}for (auto& t : writers) t.join();for (auto& t : readers) t.join();return 0;
}

典型输出(结果确定):

安全读取: 100
安全读取: 100

四、分步详解
步骤1:理解所有权独占性
  • unique_ptr 的内存布局:
    [对象指针] --> 被管理对象
    
  • 所有权转移(移动构造/赋值)会清空原指针
  • 两个线程同时修改同一指针会导致 数据竞争
步骤2:加锁保护所有权操作
std::lock_guard<std::mutex> lock(mtx);
global_ptr = std::move(new_ptr);  // 安全转移所有权
步骤3:安全访问被管理对象

若对象需要多线程访问:

class ThreadUnsafeObject {int counter = 0;
public:void increment() { ++counter; }  // 非线程安全
};std::unique_ptr<ThreadUnsafeObject> obj_ptr;void thread_work() {std::unique_ptr<ThreadUnsafeObject> local;{std::lock_guard<std::mutex> lock(mtx);local = std::move(obj_ptr);  // 独占所有权}// 现在可以安全使用 local(单线程独占)if (local) {local->increment();}// 交还所有权{std::lock_guard<std::mutex> lock(mtx);obj_ptr = std::move(local);}
}

五、编译与测试
  1. 编译命令

    g++ -std=c++17 -pthread -o unique_ptr_thread unique_ptr_thread.cpp
    
  2. 运行正确案例

    ./unique_ptr_thread
    安全读取: 100
    安全读取: 100
    

六、最佳实践总结
场景处理方案
多线程修改同一 unique_ptr必须使用 std::mutex 保护
多线程访问被管理对象通过转移所有权实现独占访问,或为对象本身添加同步机制
高频所有权转移使用 std::deque 缓冲任务,减少锁竞争
需要共享访问改用 std::shared_ptr(注意其不同的线程安全规则)

七、高级模式:所有权传递
#include <queue>
#include <mutex>template<typename T>
class SafeQueue {std::queue<std::unique_ptr<T>> queue_;std::mutex mtx_;
public:void push(std::unique_ptr<T> ptr) {std::lock_guard<std::mutex> lock(mtx_);queue_.push(std::move(ptr));}std::unique_ptr<T> pop() {std::lock_guard<std::mutex> lock(mtx_);if (queue_.empty()) return nullptr;auto ptr = std::move(queue_.front());queue_.pop();return ptr;}
};// 使用示例
SafeQueue<int> safe_queue;void producer() {safe_queue.push(std::make_unique<int>(42));
}void consumer() {auto ptr = safe_queue.pop();if (ptr) {std::cout << "消费: " << *ptr << "\n";}
}

通过合理应用这些模式,可以在多线程环境中安全高效地使用 unique_ptr,充分发挥其独占所有权的优势。

相关文章:

  • SpringAI+DeepSeek大模型应用开发——5 ChatPDF
  • 深入解析C++驱动开发实战:优化高效稳定的驱动应用
  • Spring_MVC 快速入门指南
  • 汽车免拆诊断案例 | 2011款雪铁龙世嘉车刮水器偶尔自动工作
  • wordpress 垂直越权(CVE=2021-21389)漏洞复现详细教程
  • 初识Redis · C++客户端string
  • 先导木工机床与养老领域的探索之旅
  • 仿腾讯会议项目实现——设置配置文件
  • 【特殊场景应对1】视觉设计:信息密度与美学的博弈——让简历在HR视网膜上蹦迪的科学指南
  • 6.7.图的深度优先遍历(英文缩写DFS)
  • EnlightenGAN:低照度图像增强
  • 【计算机网络 | 第一篇】计算机网络基础知识
  • 基于springBoot+vue的PC 端学习系统(源码+lw+部署文档+讲解),源码可白嫖!
  • L2-018 多项式A除以B
  • 电脑 BIOS 操作指南(Computer BIOS Operation Guide)
  • 累计达2.04亿户!中国联通首次公布5G网络用户数据
  • 使用MetaGPT 创建智能体(2)多智能体
  • 创维E900V20C-国科GK6323V100C-rtl8822cs-安卓9.0-短接强刷卡刷固件包
  • 遥感技术赋能电力设施监控:应用案例篇
  • 链表相关算法题
  • 农业未来十年展望:预计粮食单产水平将提高7.8%,达到421千克/亩
  • 老旧高层遭“连环漏水”,如何携手共治解难题?
  • 美国防部宣布整合驻叙美军部队,将减少至不足千人
  • 汕头22岁女子手术成功却意外脑死亡,家属称缺氧30分钟医生未发觉
  • 2025年世界互联网大会亚太峰会人工智能大模型论坛举行
  • 鲁比奥在法国只字不提关税,美国威胁下欧盟勉力维持统一战线