Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to force a thread waiting for signal
Forum Updated to NodeBB v4.3 + New Features

How to force a thread waiting for signal

Scheduled Pinned Locked Moved Unsolved General and Desktop
21 Posts 3 Posters 5.9k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Christian EhrlicherC Online
    Christian EhrlicherC Online
    Christian Ehrlicher
    Lifetime Qt Champion
    wrote on last edited by
    #12

    There is no difference between std::thread and QThread in your case at all. You need a running event loop to process Qt signals and slots with std::thread and with QThread.

    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
    Visit the Qt Academy at https://academy.qt.io/catalog

    1 Reply Last reply
    4
    • S Offline
      S Offline
      SimonSchroeder
      wrote on last edited by
      #13

      @Christian-Ehrlicher Actually, there is a slight difference between std::thread and QThread: If you take a plain QThread object and call start() on it, the default implementation of run() will launch an event loop. std::thread does not know about Qt and thus you have to start the event loop yourself.

      I suggest using QThread to get an event loop.

      dualD 1 Reply Last reply
      0
      • S SimonSchroeder

        @Christian-Ehrlicher Actually, there is a slight difference between std::thread and QThread: If you take a plain QThread object and call start() on it, the default implementation of run() will launch an event loop. std::thread does not know about Qt and thus you have to start the event loop yourself.

        I suggest using QThread to get an event loop.

        dualD Offline
        dualD Offline
        dual
        wrote on last edited by Christian Ehrlicher
        #14

        @SimonSchroeder thank you for answering. I tried to use QThread but it closes before receiving readyread signal. This is my implementation:

        /* Main thread: */
            int sd = tcpServer->nextPendingConnection()->socketDescriptor();
            std::cout<<"Socket descriptor: "<<sd<<std::endl;
            thread = QThread::create([sd]{
        
                sharing s(sd);
        
            });
            thread->start();
        
        /* class sharing: */
        sharing::sharing(int socketDescriptor){
            clientConnection = new QTcpSocket;
            if (!clientConnection->setSocketDescriptor(socketDescriptor)) {
                std::cout<<"Error on setting Socket Descriptor..."<<std::endl;
                return;
            }
        
            in.setDevice(clientConnection);
            in.setVersion(QDataStream::Qt_5_5);
        
            connect(clientConnection, &QIODevice::readyRead, this, &sharing::receive);
        }
        

        sharing is the class in charge of creating the QTcpSocket and of managing the file receiving. After the construction of sharing, I'd expect the thread to wait until readyread is emitted but it dosn't.

        /edit: Edited by moderator: Please use the code - tags for better readability

        1 Reply Last reply
        0
        • Christian EhrlicherC Online
          Christian EhrlicherC Online
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on last edited by
          #15

          As we already told you you need a running event loop in your thread - no matter if it's a QThread or std::thread or whatever. So please start one.

          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
          Visit the Qt Academy at https://academy.qt.io/catalog

          dualD 1 Reply Last reply
          1
          • Christian EhrlicherC Christian Ehrlicher

            As we already told you you need a running event loop in your thread - no matter if it's a QThread or std::thread or whatever. So please start one.

            dualD Offline
            dualD Offline
            dual
            wrote on last edited by dual
            #16

            @Christian-Ehrlicher What about this sentence?

            @SimonSchroeder said in How to force a thread waiting for signal:

            If you take a plain QThread object and call start() on it, the default implementation of run() will launch an event loop

            Also online i've found that Qthread has a eventLoop on the default run() method. This point is not clear to me.
            By the way, do you suggest to place a eventLoop in the sharing constructor?

            1 Reply Last reply
            0
            • Christian EhrlicherC Online
              Christian EhrlicherC Online
              Christian Ehrlicher
              Lifetime Qt Champion
              wrote on last edited by
              #17

              @dual said in How to force a thread waiting for signal:

              This point is not clear to me.

              What is not clear? QThread's run method simply executes an eventloop.

              By the way, do you suggest to place a eventLoop in the sharing constructor?

              No, it should go into the thread's main function.

              Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
              Visit the Qt Academy at https://academy.qt.io/catalog

              1 Reply Last reply
              0
              • S Offline
                S Offline
                SimonSchroeder
                wrote on last edited by
                #18

                What your last code does is placing only the constructor call into a separate thread. It will not continue running. What you should do is more like this:

                QThread *thread = new QThread();
                thread->start();
                
                sharing *s = new sharing(sd);
                s->moveToThread(thread);
                

                I haven't check with the exact syntax, so you need to check if this compiles. Notice that your sharing object also needs to be a pointer to outlive the current scope. It also should inherit from QObject so that you can move it to the other thread. Only then will your new thread's event loop handle its slots.

                You should also think about the lifetime of the thread and sharing objects. You need to delete both when the connection handled by this thread is closed.

                dualD 1 Reply Last reply
                0
                • S SimonSchroeder

                  What your last code does is placing only the constructor call into a separate thread. It will not continue running. What you should do is more like this:

                  QThread *thread = new QThread();
                  thread->start();
                  
                  sharing *s = new sharing(sd);
                  s->moveToThread(thread);
                  

                  I haven't check with the exact syntax, so you need to check if this compiles. Notice that your sharing object also needs to be a pointer to outlive the current scope. It also should inherit from QObject so that you can move it to the other thread. Only then will your new thread's event loop handle its slots.

                  You should also think about the lifetime of the thread and sharing objects. You need to delete both when the connection handled by this thread is closed.

                  dualD Offline
                  dualD Offline
                  dual
                  wrote on last edited by dual
                  #19

                  @SimonSchroeder I did some tries but still it doesn't work as expected.

                  In server.h (that is the main thread object) I defined

                  class server : public QObject
                  {
                      Q_OBJECT
                      QThread workerThread;
                  private:
                     sharing *worker;
                     void newClient();
                  }
                  

                  and in server.cpp

                  void server::newClient()
                  {
                      int sd = tcpServer->nextPendingConnection()->socketDescriptor();
                      std::cout<<"Socket descriptor: "<<sd<<std::endl;
                      if(workerThread.isRunning()){
                          std::cout<<"thread is running.. my thread id " << std::this_thread::get_id()<<std::endl;
                      }
                      else
                          std::cout<<"thread is not running.."<<std::endl;
                  
                  
                      worker = new sharing(sd);
                      connect(&workerThread, &QThread::started, worker, &sharing::doWork);
                      connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
                      worker->moveToThread(&workerThread);
                  
                      workerThread.start();
                      //workerThread.wait();
                  }
                  

                  where the if-else part is used as debug in order to check if the thread is still running when a new client tries to connect.

                  While in sharing.cpp I have

                  sharing::sharing(int socketDescriptor):socketDescriptor(socketDescriptor){
                  }
                  
                  void sharing::doWork(){
                      std::cout<<"Connecting... "<<std::endl;
                      clientConnection = new QTcpSocket;
                      if (!clientConnection->setSocketDescriptor(socketDescriptor)) {
                          std::cout<<"Error on setting Socket Descriptor..."<<std::endl;
                          return;
                      }
                  
                      in.setDevice(clientConnection);
                      in.setVersion(QDataStream::Qt_5_5);
                  
                      connect(clientConnection, &QIODevice::readyRead, this, &sharing::receive);
                      std::cout<<"Connected "<<std::endl;
                  }
                  

                  and in sharing::receive I have a switch to read json received by the client. Sharing class inherits from QObject.

                  At the moment the code works only if the workerThread.wait(); is not commented, while sharing will not receive any other readyRead when the newClient function ends. But the thread is still running when I create a new client, so I think that the eventLoop is correctly working.
                  Of course this code is not good to manage multiple clients, it is just a preliminary version because I want to reach a working version of multi-thread communication between a client and the server.

                  1 Reply Last reply
                  0
                  • Christian EhrlicherC Online
                    Christian EhrlicherC Online
                    Christian Ehrlicher
                    Lifetime Qt Champion
                    wrote on last edited by
                    #20

                    @dual said in How to force a thread waiting for signal:

                    tcpServer->nextPendingConnection()->socketDescriptor();

                    This is wrong since this already creates a QTcpSocket which is repsonsible for your socket and receives the readyRead signals.
                    You want to override QTcpServer::incomingConnection() as described in the threaded fortune server example.

                    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                    Visit the Qt Academy at https://academy.qt.io/catalog

                    dualD 1 Reply Last reply
                    2
                    • Christian EhrlicherC Christian Ehrlicher

                      @dual said in How to force a thread waiting for signal:

                      tcpServer->nextPendingConnection()->socketDescriptor();

                      This is wrong since this already creates a QTcpSocket which is repsonsible for your socket and receives the readyRead signals.
                      You want to override QTcpServer::incomingConnection() as described in the threaded fortune server example.

                      dualD Offline
                      dualD Offline
                      dual
                      wrote on last edited by
                      #21

                      @Christian-Ehrlicher your answer totally solved my problem. Thank you so much.

                      1 Reply Last reply
                      0

                      • Login

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved