Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QThread, signals and slots



  • Hi,
    I have a doubt regarding qThread.
    @void Worker::run()
    {
    qWarning()<<"Thread Started";

    tcpServerConnection=new QTcpSocket();
    qWarning()<<"SOCKET ID"<<socketDescriptor;
    
    
    if(!tcpServerConnection->setSocketDescriptor(socketDescriptor))
    {
    
           qWarning()<<"ERROR IN SOCKETDESCRIPTOR ";
                // something's wrong, we just emit a signal
           emit error(tcpServerConnection->error());
    }
    
    connect(tcpServerConnection, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection);
    connect(tcpServerConnection, SIGNAL(disconnected()), this, SLOT(disconnected()));
    qDebug() << socketDescriptor << " Client connected";
    
    qWarning()<<"SOCKET DESCRIPTOR in worker"<< tcpServerConnection->socketDescriptor();
    exec&#40;&#41;;
    

    }

    @

    this is the code of a QThread::run().
    I need to know in these connect statements the slots are executed, is these slots are executing in threads context or with the main thread?


  • Qt Champions 2017

    main thread context as worker object is owned by main thread. This is typical of signal and slot across thread.


  • Moderators

    Hi,

    If you subclass a QThread, do not add new slots to your subclass. This causes lots of problems and is considered bad practice. The "QThread documentation":http://qt-project.org/doc/qt-5/qthread.html says,

    "It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread."

    I recommend using the worker-object approach with moveToThread(). See the first example in the QThread documentation.



  • Btw., two excellent articles on this are: "You're doing it wrong":http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/ and "Threading without the headache":http://blog.qt.digia.com/blog/2006/12/04/threading-without-the-headache/ .


Log in to reply