Home > Back-end >  Is it safe for a QObject's thread affinity to be a deleted QThread?
Is it safe for a QObject's thread affinity to be a deleted QThread?

Time:08-13

Consider the following code:

QThread *thread = nullptr;
QObject *object = nullptr;

void setup() {
    QThread *thread = new QThread;
    QObject *object = new QObject;
    object->moveToThread(thread);
    thread->start();
}

void cleanup() {
    thread->exit(0);
    thread->wait(1000);
    
    if (!thread->isFinished()) {
        // handle error condition
    }
    
    delete thread;
}

void postEventToThread() {
    if (!object) { return; }
    QEvent *event = new QEvent(QEvent::User);
    qApp->postEvent(object, event);
}

If postEventToThread() is called after setup() and before cleanup(), then everything should work properly and an event will get posted to object's event queue and processed in thread.

However, what happens if cleanup() is called before postEventToThread()?

In that case object still exists and is a valid object, but its thread has been deleted. Does object automatically start behaving as though it has no thread affinity? Or is this an error?

I tested it out and it doesn't seem to print any warnings, cause any crashes, or otherwise behave badly. But I want to check and make sure that deleting an object's thread (but not the object itself) and posting an event to it is allowed in Qt before I commit to it.

CodePudding user response:

QThread starts the event loop by calling exec() and runs a Qt event loop inside the thread.

However, what happens if cleanup() is called before postEventToThread()?

thread is deleted and it's event loop exits, all event processing for object stops.

Does object automatically start behaving as though it has no thread affinity? Or is this an error?

In this case object is no longer associated with any thread. You can call it's methods from other threads, e.g main thread of application. Methods called directly on will execute in the thread that calls the method.

But I want to check and make sure that deleting an object's thread (but not the object itself) and posting an event to it is allowed in Qt before I commit to it.

It's not disallowed but does not make sense. As I've wrote before, since after object's thread is deleted, all event processing for object stops.

  • Related