views:

57

answers:

1

A portable thread specific storage reference/identity mechanism, of which boost/thread/tss.hpp is an instance, needs a way to generate a unique keys for itself. This key is unique in the scope of a thread, and is subsequently used to retrieve the object it references. This mechanism is used in code written in a thread neutral manner.

Since boost is a portable example of this concept, how specifically does such a mechanism work ?

A: 

Boost thread is portable to the pthread threading library (for unix) and the windows win32 low-level-API's. The library allows a reference to be created which is unique in each thread of execution. The global C API errno is presented as an example of this concept in Boost's documentation.


Ignore If you Want -- it's just a trace through the source code finding the function of interest

The crux of the matter begins in [boost]/boost/thread/tss.hpp with the get function of thread_specific_ptr and the reset function -- i.e., the aquisition and the destruction, respectively, of the object referenced. Note: the data object is not placed in the reference of thread_specific_ptr's ctor, or destroyed by the dtor. The get and reset function call set_tss_data and get_tss_data. Focusing just on the setting aspect of the functionality, the important function call, get_current_thread_data, indirects via the cpp file [boost]/libs/thread/src/[libname]/thread.cpp via a chain of function calls. In get_current_thread_data there is a function call create_current_thread_tls_key and this is the function that will create a unique identifier for the thread_specific_ptr object.


create_current_thread_tls_key calls TlsAlloc() on win32 (link) and pthread_key_create for pthread (link). These calls assure that upon initialization of the ptr, the ptr receives a unique identifier usable in an API-specific manner to retrieve the object's data. The specific threading API uses the thread-id (context specific and resolved by the library itself) and the object identifier to return the object specific to the context of a certain thread.

Hassan Syed