C++ Boost

Boost.Threads

tss


Introduction
Header
Synopsis
Members
Example

Introduction

The tss 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 that rely on global data thread-safe.

Header

#include <boost/thread/tss.hpp>

Synopsis

namespace boost {

class tss : boost::noncopyable
{
public:
    tss();
    ~tss();

    void* get() const;
    bool set(void* value);
};

} // namespace boost

Members


Constructor

tss();

Effects: Constructs a tss object for accessing thread specific storage.


Destructor

~tss();

Effects: Destroys the tss object.

Notes: This does not destroy any data that may be stored in the thread specific storage.


get

void* get() const;

Effects: Retrieves the thread specific storage for the current thread.

Notes: If the current thread has not previously called set() the value returned is 0.


set

bool set(void* value);

Effects: Sets the thread specific storage for the current thread. Returns false on failure.

Notes: Any previous value is simply overwritten and any data that may have been pointed to by the previous value is not destroyed.


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 19 July, 2001

Copyright William E. Kempf 2001 all rights reserved.