Nominate our 2022 Qt Champions!

QThread and Main Thread are not executing concurrently.

  • Hi guys.
    As the title suggests, I'm running into some issues getting my main thread and a subthread to run concurrently.
    The worker, at the moment, is just a dummy that executes a while(1) infinite loop. There used to be a blocking call in the while(1) loop, but this was removed to see if a shared resource was causing the issue.

    class worker : public QObject
        libusb_context *ctx;
    public slots:
        void handle(){

    To set up the worker and its thread, I use the code below:
    Note that isoHandler and workerThread are both (private) members of the controller class - a QWidget derivative.

        isoHandler = new worker();
        workerThread = new QThread();
        isoHandler->ctx = ctx;
        connect(workerThread, SIGNAL(started()), isoHandler, SLOT(handle()));

    Oddly, the subthread pre-empts the main one and prevents the GUI from displaying at all. Lowering its priority to Low doesn't change this. Commenting out the workerThread->start() is the only way to get the GUI to run. Or course, this is only because the subthread never starts.

    Does anyone know what could be going on? I've Googled it, but apparently this is usually caused by a flood of events and I obviously don't have any going on here.


  • Lifetime Qt Champion

    @espocjo said in QThread and Main Thread are not executing concurrently.:


    Is the handle() slot called and what are you doing there?

  • handle() is connected to the started() slot in the sub-thread.
    It is never directly called from the main thread.

    All it does is block with a while(1) loop. It used to run a (blocking) libusb call, but I removed that code to try and isolate the fault. I wanted to make sure the issue was with QThread and not libusb.


  • Lifetime Qt Champion

    it does seems ok, code wise.
    Could you try this small sample
    and see if you got same result like me ( main and thread is runing ) or something else-

  • I looked more closely at the console output and found the error - it was a piece of old code that called workerThread->wait() in the destructor of the object that created workerThread just after workerThread->quit(). Copied straight from the documentation, without even a thought as to what it actually did.

    Of course, since it was permanently blocking, the sub-thread never got back to the event loop and therefore never returned. So the main thread would wait forever, and the subthread would never terminate...

    Not sure if there's terminology for this, since I'm very new to multi-threaded programming, but I get the feeling that this kind of thing is a rookie mistake.

    Thanks again, though!

Log in to reply