QThreadStorage Class
template <typename T> class QThreadStorage
The QThreadStorage class provides per-thread data storage. More…
| Header | #include <QThreadStorage> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Core) |
| Module | Nt Core C++ Classes |
List of all members, including inherited members
Public Functions
| QThreadStorage() | |
| ~QThreadStorage() | |
| bool | hasLocalData() const |
| T & | localData() |
| T | localData() const |
| void | setLocalData(T data) |
Detailed Description
A QThreadStorage object keeps one value for each thread that uses it, so a function that is called from several threads can have its own cache in each. A thread's value is destroyed when the thread exits, or earlier if the QThreadStorage is destroyed in that thread or the value is replaced.
QThreadStorage<QString *> prefix;
void log(const QString &text)
{
if (!prefix.hasLocalData())
prefix.setLocalData(new QString(makePrefix()));
write(*prefix.localData() + text);
}
See also QThread and QThreadPool.
Differences from Qt
Destroying a QThreadStorage destroys the value of the calling thread only. The values of other threads stay until those threads exit. There is no isDestroyed().
Member Function Documentation
QThreadStorage::QThreadStorage()
Constructs an empty storage. No thread has data in it.
QThreadStorage::~QThreadStorage()
Destroys the storage and the calling thread's value in it.
bool QThreadStorage::hasLocalData() const
Returns true if the calling thread has data in this storage; otherwise returns false.
See also localData() and setLocalData().
T & QThreadStorage::localData()
Returns a reference to the data that the calling thread stores here. If the thread has none yet, a default-constructed value is stored first.
See also hasLocalData() and setLocalData().
T QThreadStorage::localData() const
This is an overloaded function.
Returns a copy of the data that the calling thread stores here, or a default-constructed value if it has none. Nothing is stored.
void QThreadStorage::setLocalData(T data)
Stores data as the calling thread's value. Data the thread stored before is destroyed. If T is a pointer type, the storage owns the object it points to and deletes it, and passing nullptr clears the data. The data is destroyed when the thread exits.
See also localData() and hasLocalData().