C++11標準ライブラリのスマートポインタstd::shared_ptr
では、C++標準ライブラリの既定レベルのスレッド安全性(→id:yohhoy:20120513)を提供する。
- 同一オブジェクトを指していたとしても、異なる2つの
shared_ptr
オブジェクトは異なるスレッドからそれぞれ安全に read / modify 操作を行える。 - 単一の
shared_ptr
オブジェクトに対して、異なるスレッドからの操作が全て read アクセスであれば安全。
C++11(N3337) 20.7.2.2/p4より引用。
For purposes of determining the presence of a data race, member functions shall access and modify only the
shared_ptr
andweak_ptr
objects themselves and not objects they refer to. Changes inuse_count()
do not reflect modifications that can introduce data races.
gccとMSVCの両処理系、および Boost.SmartPointer ライブラリでもC++11標準が要求するとおりのスレッド安全性を提供する。
gcc(libstdc++)
参照カウンタ操作のロックポリシーは、libstdc++ビルド構成・環境に応じて下記のうち何れかが選択される。なお、特に理由が無ければロックフリー実装が優先される。
- 組込みatomic CAS操作によるロックフリー実装
- ミューテックスオブジェクトによるロックベース実装(組込みatomicが利用できないとき)
- シングルスレッド向けのロックなし実装(--enable-threads指定無しビルド)
Requirements
http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html
(snip)
At the time of writing the C++0x working paper doesn't mention how threads affect shared_ptr, but it is likely to follow the existing practice set byboost::shared_ptr
. The shared_ptr in libstdc++ is derived from Boost's, so the same rules apply.
メモ:そもそもlibstdc++のstd::shared_ptr
は "Uses code from boost::shared_ptr." 記載どおりBoost.SmartPointerと同一コード?
MSVC
Thread Safety
http://msdn.microsoft.com/en-us/library/bb982026.aspx
Multiple threads can read and write differentshared_ptr
objects at the same time, even when the objects are copies that share ownership.
Boost.SmartPointer
Thread Safety
shared_ptr
objects offer the same level of thread safety as built-in types. Ashared_ptr
instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Differentshared_ptr
instances can be "written to" (accessed using mutable operations such asoperator=
orreset
) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)(snip)
Starting with Boost release 1.33.0,shared_ptr
uses a lock-free implementation on the following platforms:http://www.boost.org/libs/smart_ptr/shared_ptr.htm#ThreadSafety
- GNU GCC on x86 or x86-64;
- GNU GCC on IA64;
- Metrowerks CodeWarrior on PowerPC;
- GNU GCC on PowerPC;
- Windows.
マクロBOOST_SP_DISABLE_THREADS
を定義するとシングルスレッド用の内部実装に、マクロBOOST_SP_USE_PTHREADS
を定義するとロックフリー実装ではなくPThreadsミューテックスによる内部実装へと切り替えることが出来る。
関連URL