Nominate our 2022 Qt Champions!

Signal and Slot Two Threads

  • I have a Problem. I am using 2 Threads, so that my GUI cannot lock up.

    I start both threads and htop is showing me two threads.

    For now, I force my working thread to enter an infinite loop once a slot is triggered.

    In my GUI Thread I emit the corresponding signal, but the whole program locks up.

    I have connected the two threads like this.

    @ connect(this, SIGNAL(setswitch(QString,int)), this->thread2, SLOT(setswitch(QString, int)), Qt::QueuedConnection);

    When I change the signal and slot from QString to char* the main thread stays alive, just like expected.
    When I printed the char* in the working thread before entering the infinite loop, it only shows bogus.

    What did I miss? Why can I not connect between the two threads using the QString.

  • could you provide more code? how do you create those threads?

    maybe helps, there are some well explained examples.

  • I inherited from QThread and reimplemented run like this

    @void thread_class::run(){
    std::cout << "Starting Thread 2" <<std::endl;

    in the main Thread I start the second thread like this.

    @ thread = new thread_class();

  • And the object that actually implements the slot with the infinate loop? Where do you create it, and what else do you do with it?

  • The thread_class is the object that I send to the infinite loop.

    @class thread_class : public QThread
    void run();

    public slots:
    void setswitch(QString board, int num);



    The slot is implemented like this.

    @void thread_class::setswitch(QString board, int num){
    std::cout << qPrintable(board) << std::endl;

    I just create this thread inside another class.

  • You are doing it wrong (TM)

    See the excellent "article": on the Wiki on how to deal with Threads, objects, signals & slots and events.

  • Oh ok, thanks. I see that its not working since this and this->thread are Objects in the same thread.
    So I have changed it like this.

    @class Worker : public QObject

    public slots:
    void doWork() {
    /* ... */

    /* ... */
    QThread thread;
    Worker worker;
    connect(obj, SIGNAL(workReady()), &worker, SLOT(doWork()));

    So I have my class that does the work and I move this instance to the second thread. Now the Objects are no longer in the same thread and the QueuedConnection works.

    Thank you.

  • Indeed. You have to remember that QThread is not a thread, it only manages one.

    QThread can be subclassed (and it can make sense to do so), but you have to remember that only that what happens in the run() method actually happens in the other thread. Everything else happens in the thread that your QThread itself lives in. New signals and slots should be about the management of the thread, not about the actual work it is supposed to do.

Log in to reply