|
|
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.
Template thread_specific_ptr stores a pointer to an
object obtained via new on a thread-by-thread basis and
calls delete on the contained pointer when the thread terminates. Each
thread initially stores the null pointer in each
thread_specific_ptr instance.
The template thread_specific_ptr is useful in the
following cases:
#include <boost/thread/tss.hpp>
namespace boost {
template <typename T>
class thread_specific_ptr : private boost::noncopyable // Exposition only.
// Class thread_specific_ptr meets the NonCopyable requirement.
{
public:
thread_specific_ptr();
~thread_specific_ptr();
T* get() const;
T* operator->() const;
T& operator*() const;
T* release();
void reset(T* p=0);
};
} // namespace boost
thread_specific_ptr();
Postconditions: A thread specific storage has been reserved for use by *this in all threads, with each thread initially storing a null pointer.
Requires: The expression delete get() is well
formed.
Throws: boost::thread_resource_error if the
necessary resources can not be obtained.
Notes: There is an implementation specific limit to the number of thread specific storage objects that can be created, and this limit may be small.
~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.
Notes: Each thread initially returns 0.
T* operator->() const;
Returns: get()
T& operator*() const;
Returns: get()
Requires: get() != 0
T* release();
Returns: get()
Postcondition: *this holds the null pointer for the current thread.
void reset(T* p=0);
Effects: If get()!= p then delete
get().
Postconditions: *this holds the pointer
p for the current thread.
Notes: The pointer will be deleted when the thread terminates.
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <cassert>
boost::thread_specific_ptr<int> value;
void increment()
{
int* p = value.get();
++*p;
}
void thread_proc()
{
value.reset(new int(0)); // initialize the thread's storage
for (int i=0; i<10; ++i)
{
increment();
int* p = value.get();
assert(*p == i+1);
}
}
int main(int argc, char* argv[])
{
boost::thread_group threads;
for (int i=0; i<5; ++i)
threads.create_thread(&thread_proc);
threads.join_all();
}
Revised 05 November, 2001
© Copyright William E. Kempf 2001 all rights reserved.