C++ Boost

Boost.Threads

thread_specific_ptr


Introduction
Header
Synopsis
Members
Example

Introduction

The thread_specific_ptr class defines an interface for using thread specific storage. Thread specific storage is data associated with individual threads and is often used to make operations thread-safe that rely on global data.

Header

#include <boost/thread/tss.hpp>

Synopsis

namespace boost {

template <typename T>
class thread_specific_ptr : private boost::noncopyable
{
public:
    thread_specific_ptr();
    ~thread_specific_ptr();

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

} // namespace boost

Members


Constructor

thread_specific_ptr();

Postconditions: A thread specific storage slot has been reserved for use by *this in all threads.

Requires: The expression delete get() is well formed.

Notes: There may be an implementation specific limit to the number of thread specific storage slots that can be created, and this limit may be small. No object is actually created for storage in any running thread.


Destructor

~thread_specific_ptr();

Notes: Does not destroy any data that may be stored in any thread's thread specific storage. For this reason you should not destroy a thread_specific_ptr object until you are certain there are no threads running that have made use of its thread specific storage.


get

T* get() const;

Returns: The object stored in thread specific storage for the current thread for *this.

Requires: The experession new T() is well formed.

Notes: If the current thread has not previously accessed it's thread specific storage for *this then an object of type T shall be default constructed and stored.


Smart Pointer Operations

T* operator->() const;

Returns: get()

T& operator*() const;

Returns: get()

Requires: get() != 0


Example Usage

#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <cassert>

boost::tss value;

void increment()
{
   int* p = static_cast(value.get());
   ++*p;
}

void thread_proc()
{
   value.set(new int(0)); // initialize the thread's storage
   for (int i=0; i<10; ++i)
   {
       increment();
       int* p = static_cast(value.get());
       assert(*p == i+1);
   }
   delete value.get();
}

int main(int argc, char* argv[])
{
   boost::thread::thread_group threads;
   for (int i=0; i<5; ++i)
      threads.create(&thread_proc);
   threads.join_all();
}

Revised 01 August, 2001

© Copyright William E. Kempf 2001 all rights reserved.