TLS (Thread Local Storage)
Table of Contents

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:

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License

Subscription expired — please renew

Pro account upgrade has expired for this site and the site is now locked. If you are the master administrator for this site, please renew your subscription or delete your outstanding sites or stored files, so that your account fits in the free plan.