|
|
Boost.Threadsthread_specific_ptr |
Introduction
Header
Synopsis
Members
Example
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.
#include <boost/thread/tss.hpp>
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
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.
~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.
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.
T* operator->() const;
Returns: get()
T& operator*() const;
Returns: get()
Requires: get() != 0
#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.