简体   繁体   中英

What is the QThreadData of a QObject which is created within std::thread or pthread_create

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(&current_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 (eg QThread).

My questions are:

  1. Is my understanding correct?
  2. If yes, does not this cause a QueuedConnection to a slot in this QObject to be called in a completely wrong eventLoop (the event loop which is associated with the last "currentThreadData" set by the QT)
  3. if no, how can QT understand that a Qobject created within pthread_create is not associated with any event loop?

(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.)

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM