Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

 概述

        線程本地化存儲允許多個線程對像擁有特定數據的獨立拷貝. 單線程程序通常使用的的靜態數據和全局數據在多線程程序中會引發訪問競爭,死鎖,或者數據破壞 . 一個例子就是 C運行庫中的 errno 變量, 該變量放C標準庫中函數的錯誤代碼. 對於支持多線程的編譯器來說,為每個線程提供一個獨立的errno 是常見的做法,以此避免多個線程競爭對它的訪問和更新(這也是POSIX 標準要求的).

        儘管編譯器通常提供一些形式的語法擴展來方便標記線程本地存儲(比如用於 static 或名字空間內變量聲明前的 __declspec(thread)__thread 標記), 但是這些支持是不可移植的, 也僅限於某些用途, 比如只支持 POD 類型.

boost::thread_specific_ptr實現的可移植的線程本地化存儲

    boost::thread_specific_ptr 提供了一個線程本地化存儲機制的可移植實現,在支持Boost.Thread的所有平台上適用. 每個Each instance of boost::thread_specific_ptr represents 指針指向一個對像a pointer to an object (比如such as errno) where這些對像要求在不同的線程間有不同的值 each thread must have a distinct value. 當前線程對應的對象的值可以通過成員函數The value for the current thread can be obtained using the get() member獲取 function, or by 或是通過using the * and -> pointer 操作deference operators. 這些對象的初始值為Initially the pointer has a value of NULL in each thread, but 需要通過函數the value for the current thread can be set using the reset() member 改變當前線程對應的值function.

       如果通過reset()boost::thread_specific_ptr 的指向改變, 那麼在此之前的值會被清理, 另外, 存儲的值可以通過成員函數release() 置為NULL, 該函數同時返回這個值, 這樣應用程序可以有機會銷毀這個值關聯的對象.

 線程退出時清理

       當一個線程退出, boost::thread_specific_ptr實例 所關聯的對象會被銷毀. 通常銷毀的動作通過對被指向的對象調用delete完成, 這個行為也可以通過向 boost::thread_specific_ptr 對像構造時傳遞一個清理函數func()來重載.此時, 所指向對像通過調用 func(p) 來銷毀 .這些清理函數調用順序不是確定的 . 如果一個清理函數將 對像關聯的值設置為一個被清理過的值, 這個值會被添加到清理列表中. 當所有 boost::thread_specific_ptr 對像被置為空時,清理過程結束.

#include <boost/thread/tss.hpp>

template <typename T>
class thread_specific_ptr
{
public:
thread_specific_ptr();
explicit thread_specific_ptr(void (*cleanup_function)(T*));
~thread_specific_ptr();

T* get() const;
T* operator->() const;
T& operator*() const;

T* release();
void reset(T* new_value=0);
};

要求:

delete this->get() 有意義.

效果:

構造一個 thread_specific_ptr  對象,存儲一個T類型的指針,指向線程本地化對像. 在函數 reset() 被調用, 或者線程退出時,默認基於delete 的清理函數會被調用來銷毀線程本地的對象.

拋出:

如果出錯,拋出boost::thread_resource_error異常.

要求:

cleanup_function(this->get()) 調用不拋出異常.

效果:

構造一個 thread_specific_ptr  對象,存儲一個T類型的指針,指向線程本地化對像. 在函數 reset() 被調用, 或者線程退出時,基於cleanup_function的清理函數會被調用來銷毀線程本地的對象.

拋出:

如果出錯,拋出boost::thread_resource_error異常.

效果:

調用函數 this->reset() to 清理當前線程相關本地存儲對像, 並銷毀自身(*this).

拋出:

無.

[Note]

必須小心確保boost::thread_specific_ptr 對像銷毀後,線程不再調用該對象的函數.

返回值:

當前線程相關本地存儲對象的指針.

拋出:

無.

[Note]

boost::thread_specific_ptr 關聯對像初始值為 NULL.

返回值:

this->get()

拋出:

無.

要求:

this->get() 返回非空值.

返回值:

*(this->get())

拋出:

無.

效果:

如果If this->get()!=new_value 並且 this->get()返回非空(non-NULL), 調用對應的清理函數, delete this->get() 或者 cleanup_function(this->get()) . 將 new_value 保存為和當前線程關聯的指針

後置條件:

this->get()==new_value

拋出:

如果出錯,拋出boost::thread_resource_error異常.

效果:

返回 this->get(), 將當前線程關聯的指針置空( NULL),並不清理關聯對像.

後置條件:

this->get()==0

拋出:

無.


PrevUpHomeNext