Question about Threads



  • Hi,

    I have a question about using threads.

    Until know I derived my classes form QObject and then I made a thread and moved my instances to a thread like this:

    QThread* thread = new QThread;
    Worker* worker = new Worker();
    worker->moveToThread(thread);
    connect(thread, SIGNAL(started()), worker, SLOT(process()));
    connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
    connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
    

    I always emitted finished and used the thread only for the function which was connected with the start signal of the thread.

    Now I would like to start a thread which is running all the time while the GUI thread is running.
    The worker has several methods I would like to call from the GUI thread using signal slots.

    So would it work just to do it like this:

    QThread* thread = new QThread;
    Worker* worker = new Worker();
    worker->moveToThread(thread);
    thread->start();*/
    
    //Are the following methods executed in the thread of the worker object or in the GUI thread?
    worker->method1(); 
    worker->method2();
    worker->method3(); 
    

    If I would connect methods with the Signal-Slot-Mechanism without specifying a connection type QT would automatically use a Queued Connection, right?

    Thank you very much :-)


  • Moderators

    //Are the following methods executed in the thread of the worker object or in the GUI thread?
    worker->method1(); 
    worker->method2();
    worker->method3();
    

    All these calls will be executed in the thread calling them.

    I would suggest to provide the connection type explicitly, so you do not do any assumption about the type Qt selects by default.



  • Thanks,

    this means if I use always signals and slots and specify the connection type to "QueuedConnection" the members would be executed in the worker thread which always runs in the example I provided?


  • Moderators

    Yes, it should be like this



  • @RolBri

    As an alternative, you can use QMetaObject::invokeMethod instead of signals and slots. FYI



  • Thank you all very much :-)

    I tested both and both works fine.
    The QMetaObject::invokeMethod is really convenient :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.