|
|
Boost.Threadstss |
Introduction
Header
Synopsis
Members
Example
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.
#include <boost/thread/tss.hpp>
namespace boost {
class tss : boost::noncopyable
{
public:
tss();
~tss();
void* get() const;
bool set(void* value);
};
} // namespace boost
tss();
Effects: Constructs a tss object for accessing thread specific storage.
~tss();
Effects: Destroys the tss object.
Notes: This does not destroy any data that may be stored in the thread specific storage.
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.
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.
#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.