boost::shared_ptr的線程安全性

boost::shared_ptr的win32實現中,沒有使用類似mutex機制卻能夠實現線程安全。

線程安全主要就是保證引用計數機制的線程安全

win32實現中關鍵在於使用了
BOOST_INTERLOCKED_DECREMENT以及BOOST_INTERLOCKED_INCREMENT

在interlocked.hpp中可以看到
 

#if defined( BOOST_USE_WINDOWS_H )

# include <windows.h>

# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement
# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement
# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange

windows提供了InterlockedIncrement以及InterlockedDecrement兩個api。
實現 鎖加,鎖減操作。

boost::shared_ptr的win32thread實現中,沒有使用類似mutex機制卻能夠實現線程安全。
boost::shared_ptr的pthread實現中,使用了mutex機制來保證線程安全。

遺留疑問:
InterlockedIncrement和InterlockedDecrement內部是否也使用了mutex機制?


Boost 文檔對於 shared_ptr 的線程安全有一段專門的記述,內容如下: 
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.) 
Any other simultaneous accesses result in undefined behavior. 
翻譯爲中文如下: 
shared_ptr 對象提供與內建類型一樣的線程安全級別。一個 shared_ptr 實例可以同時被多個線程“讀”(僅使用不變操作進行訪問)。不同的 shared_ptr 實例可以同時被多個線程“寫入”(使用類似 operator= 或 reset 這樣的可變操作進行訪問)(即使這些實例是拷貝,而且共享下層的引用計數)。 
任何其它的同時訪問的結果會導致未定義行爲。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章