Reputation: 689
Whenever a QObject is created, QT assigns a QThreadData to the QObject in its constructor. Among other things, this QThreadData is then used to check the existence of a event loop associated with the QObject.
When Qt threading facilities are used (for instance QThread or implicitly via QCoreApplication in single threaded application), Qt assigns meaningful values to QThreadData and everything works as expected.
However, the following source code implies that a QObject created within a manual system interface threading facility (for instance in a pthread_create or std::thread), will simply copy the last QThreadData from the last QT threading facility call: (The code is copied from /qt5/qtbase/src/corelib/thread/qthread_unix.cpp and HAVE_TLS is defined)
// Utility functions for getting, setting and clearing thread specific data.
static QThreadData *get_thread_data()
{
#ifdef HAVE_TLS
return currentThreadData;
#else
pthread_once(¤t_thread_data_once, create_current_thread_data_key);
return reinterpret_cast<QThreadData *>(pthread_getspecific(current_thread_data_key));
#endif
}
In the above code sample, "currentThreadData" is a static variable which is previously set by the QT during any QT threading facility call (e.g. QThread).
My questions are:
(Please note that I always assume that parent of a QObject is set to NULL. Because when parent is set for a QObject, QThreadData is directly copied from that parent and everything again works correctly.)
Upvotes: 1
Views: 659
Reputation: 12889
I'm not sure I entirely understand the question. However, when you say...
"currentThreadData" is a static variable which is previously set by the QT during any QT threading facility call (e.g. QThread).
...you're missing one important point: currentThreadData
is also declared thread local
.
In the code base I'm looking at (Qt 5.13.0) it is...
static __thread QThreadData *currentThreadData = 0;
Where __thread
is a compiler specific extension which essentially provides the same thread local storage duration as the c++11
keyword thread_local
.
Hence, the currentThreadData
variable as seen by one thread is completely separate from the currentThreadData
variable seen by any other thread.
Upvotes: 3