Introduce tls_ptr_t

This is a lightweight wrapper around the pthread methods to access thread local memory.
This commit is contained in:
Ronald Wampler
2015-08-06 10:51:46 -04:00
committed by Allan Odgaard
parent 60050cf026
commit f3d1abaeca

View File

@@ -0,0 +1,36 @@
#ifndef TLS_PTR_H_186F0BAB
#define TLS_PTR_H_186F0BAB
namespace oak
{
template<typename T>
struct tls_ptr_t
{
tls_ptr_t () { pthread_key_create(&_key, destructor); }
~tls_ptr_t () { }
tls_ptr_t (tls_ptr_t const& rhs) = delete;
tls_ptr_t& operator= (tls_ptr_t const& rhs) = delete;
T& operator* () const { return *get(); }
T* operator-> () const { return get(); }
private:
T* get () const
{
T* valuePtr = static_cast<T*>(pthread_getspecific(_key));
if(!valuePtr)
{
pthread_setspecific(_key, new T);
valuePtr = static_cast<T*>(pthread_getspecific(_key));
}
return valuePtr;
}
static void destructor (void* valuePtr) { delete static_cast<T*>(valuePtr); }
pthread_key_t _key;
};
} /* oak */
#endif /* end of include guard: TLS_PTR_H_186F0BAB */