QThreadStorage Class

The QThreadStorage class provides per-thread data storage. More...

Header: #include <QThreadStorage>
qmake: QT += core

Note: All functions in this class are thread-safe.

Public Functions

QThreadStorage()
~QThreadStorage()
bool hasLocalData() const
T &localData()
T localData() const
void setLocalData(T t)

Detailed Description

The QThreadStorage class provides per-thread data storage.

QThreadStorage is a template class that provides per-thread data storage.

The setLocalData() function stores a single thread-specific value for the calling thread. The data can be accessed later using localData().

The hasLocalData() function allows the programmer to determine if data has previously been set using the setLocalData() function. This is also useful for lazy initializiation.

If T is a pointer type, QThreadStorage takes ownership of the data (which must be created on the heap with new) and deletes it when the thread exits, either normally or via termination.

For example, the following code uses QThreadStorage to store a single cache for each thread that calls the cacheObject() and removeFromCache() functions. The cache is automatically deleted when the calling thread exits.


  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);
  }

Caveats

  • The QThreadStorage destructor does not delete per-thread data. QThreadStorage only deletes per-thread data when the thread exits or when setLocalData() is called multiple times.
  • QThreadStorage can be used to store data for the main() thread. QThreadStorage deletes all data set for the main() thread when QApplication is destroyed, regardless of whether or not the main() thread has actually finished.

See also QThread.

Member Function Documentation

QThreadStorage::QThreadStorage()

Default constructs an instance of QThreadStorage.

QThreadStorage::~QThreadStorage()

Destroys the instance of QThreadStorage.

bool QThreadStorage::hasLocalData() const

T &QThreadStorage::localData()

See also setLocalData().

T QThreadStorage::localData() const

void QThreadStorage::setLocalData(T t)

See also localData().