Skip to content

Commit

Permalink
update _posts/2024-05-16-shared_ptr_thread_safe.md
Browse files Browse the repository at this point in the history
  • Loading branch information
hxf0223 committed Nov 6, 2024
1 parent d7f36a3 commit 0c17953
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions _posts/2024-05-16-shared_ptr_thread_safe.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: std::shared_ptr 线程安全
title: std::shared_ptr 线程安全及性能考量
date: 2024-05-16 +0800 # 2022-01-01 13:14:15 +0800 只写日期也行;不写秒也行;这样也行 2022-03-09T00:55:42+08:00
categories: [cpp]
tags: [cpp] # TAG names should always be lowercase
Expand All @@ -10,6 +10,8 @@ mermaid: true
# pin: true
---

## 1. 线程安全 ##

根据[cppreference](https://en.cppreference.com/w/cpp/memory/shared_ptr)的描述,`std::shared_ptr`线程安全如下(机器翻译):

1. 如果是每个线程都拥有自己的`std::shared_ptr`对象,则针对线程自己的`std::shared_ptr`对象,其所有成员函数都是线程安全的;
Expand All @@ -18,6 +20,22 @@ mermaid: true

原文:

```text
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different shared_ptr objects without additional synchronization even if these objects are copies and share ownership of the same object. If multiple threads of execution access the same shared_ptr object without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur; the std::atomic<shared_ptr> can be used to prevent the data race.
```

总结:

1. 多线程拷贝同一个`std::shared_ptr`对象,是线程安全的(引用计数是线程安全的)。
2. 多线程访问`std::shared_ptr`指向的同一个内存对象时,访问`const`成员函数是线程安全的。
3. 其余情况,需要使用同步。

## 2. 性能考量 ##

1. 使用`std::make_shared``std::make_shared`将被指向对象的内存分配与`控制块`的内存分配合并为一次分配;
2. `std::make_shared`的性能接近`new`;但`std::shared_ptr<T>(new T)`耗时较明显;
3.`x86`平台,`std::shared_ptr`的访问时间应该接近`T*`;但`ARM`平台应该会有明显的性能差异;

## 3. 更多资料 ##

* [合集 - C++系列(18) C++: weak_ptr到底有什么用?](https://www.cnblogs.com/qiangz/p/17843039.html)
* [合集 - C++系列(18) C++ 高效使用智能指针的8个建议](https://www.cnblogs.com/qiangz/p/17904768.html)
* [合集 - C++系列(18) C++: 16个基础的C++代码性能优化实例](https://www.cnblogs.com/qiangz/p/18270166)

0 comments on commit 0c17953

Please sign in to comment.