TLS (Thread Local Storage)
TlsKey
TlsKey is a simple wrapper class of pthread TLS procedures and windows TLS APIs.
Specification:
class TlsKey { public: void create(); void clear(); void put(void* p) const; void* get() const; };
TlsPtr
Specification:
template <class Type> class TlsPtr { public: typedef Type* pointer; typedef Type& reference; public: explicit TlsPtr(TlsKey key); operator pointer() const; pointer operator->() const; pointer operator=(pointer p); reference operator*() const; bool operator!() const; };
Example:
void testTlsPtr() { TlsKey key; key.create(); TlsPtr<Obj> obj(key); obj = new Obj(1); obj->trace(log); delete obj; obj = new Obj(2); obj->trace(log); delete obj; key.clear(); }
TlsObject
Specification:
template <class Type> class TlsFactory { public: enum { has_cleanup = 1 }; static Type* create() { return new Type; } static void cleanup(void* p) { delete (Type*)p; } }; template < class Type, class Factory = TlsFactory<Type>, class ThreadModel = InitializerThreadModel> class TlsObject { public: void init(); void term(); Type& get(); const TlsKey& storage() const; };
TlsObject::init() can be called more than once. each call to TlsObject::init() must be balanced by a corresponding call to TlsObject::term().
Example:
TlsObject<Obj> _tls_obj; void testTlsObject() { _tls_obj.init(); { Obj& obj = _tls_obj.get(); // Use obj to do something... } _tls_obj.term(); }
Related Topic:
page_revision: 3, last_edited: 1209120029|%e %b %Y, %H:%M %Z (%O ago)





