Tomáš Zato Tomáš Zato - 1 month ago 9
C++ Question

Can I use Qt thread ID to create unique cache for every thread?

I want to cache lazy loaded objects that are not thread safe. Every thread should have it's own group of objects.

My idea is to create

QMap<int, MyObject>
and access this map by thread ID that I get using
QThread::currentThreadId()
. The map itself would be protected by read/write mutex (that is, unique lock for writing, shared lock for reading). It will not be acessed often.

I am not sure if it's really a good idea. Are there any problems with this approach?

Answer Source

Try http://doc.qt.io/qt-5/qthreadstorage.html.

Examplecode:

QThreadStorage<QCache<QString, SomeClass> > caches;

void cacheObject(const QString &key, SomeClass *object)
{
    caches.localData().insert(key, object);
}

void removeFromCache(const QString &key)
{
    if (!caches.hasLocalData())
        return;

    caches.localData().remove(key);
}