yohhoyの日記

技術的メモをしていきたい日記

shared_ptrとスレッド安全性

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 and weak_ptr objects themselves and not objects they refer to. Changes in use_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
(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 by boost::shared_ptr. The shared_ptr in libstdc++ is derived from Boost's, so the same rules apply.

http://gcc.gnu.org/onlinedocs/libstdc++/manual/shared_ptr.html

メモ:そもそもlibstdc++std::shared_ptrは "Uses code from boost::shared_ptr." 記載どおりBoost.SmartPointerと同一コード?

MSVC

Thread Safety
Multiple threads can read and write different shared_ptr objects at the same time, even when the objects are copies that share ownership.

http://msdn.microsoft.com/en-us/library/bb982026.aspx

Boost.SmartPointer

Thread Safety
shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) 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

マクロBOOST_SP_DISABLE_THREADSを定義するとシングルスレッド用の内部実装に、マクロBOOST_SP_USE_PTHREADSを定義するとロックフリー実装ではなくPThreadsミューテックスによる内部実装へと切り替えることが出来る。

関連URL