Thread Safety of shared_ptr
2015-05-30 16:51
274 查看
shared_ptrobjects offer the same level of thread safety as built-in types. A
shared_ptrinstance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different
shared_ptrinstances can be "written to" (accessed using mutable operations such as
operator=or
reset) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath.)
Any other simultaneous accesses result in undefined behavior.
Examples:
shared_ptr<int> p(new int(42)); //--- Example 1 --- // thread A shared_ptr<int> p2(p); // reads p // thread B shared_ptr<int> p3(p); // OK, multiple reads are safe //--- Example 2 --- // thread A p.reset(new int(1912)); // writes p // thread B p2.reset(); // OK, writes p2 //--- Example 3 --- // thread A p = p3; // reads p3, writes p // thread B p3.reset(); // writes p3; undefined, simultaneous read/write //--- Example 4 --- // thread A p3 = p2; // reads p2, writes p3 // thread B // p2 goes out of scope: undefined, the destructor is considered a "write access" //--- Example 5 --- // thread A p3.reset(new int(1)); // thread B p3.reset(new int(2)); // undefined, multiple writes
相关文章推荐
- shared_ptr
- boost::shared_ptr使用技巧
- 智能指针
- auto_ptr与shared_ptr 的区别
- shared_ptr使用
- shared_ptr 共享指针 智能指针 简介
- 读书笔记--智能指针
- 初探boost之smart_ptr库学习笔记
- Effective C++ 对象管理资源
- C++ - "shared_ptr" 拆分智能指针(smart pointer)
- C++ - 在文件中 查找 指定的词 出现的行号 (shared_ptr)
- shared_ptr智能指针源码剖析
- 智能指针shared_ptr
- C++ 智能指针的使用
- 使用 shared_ptr
- 裸指针和智能指针的性能对比
- 《C++ Primer第五版》读书笔记(10)-DYNAMIC MEMORY
- C++ 11智能指针之shared_ptr
- 将NULL传递给C++字符串形参
- boost智能指针之shared_ptr和weak_ptr