title: How to stop thread - Qthread
body: <p>I have to start/stop a thread on press of two different buttons.<br>
  Please suggest my code is correct or not. Do I have missed something in the connect() call ?</p>
  
  <p><code>Problem</code> i am facing is that after calling quit() on my thread, then i wait for my thread to finish, but wait() call on thread <code>never returns true</code>, and my <code>program is stuck in</code> , while(!m_deviceThread.wait())</p>
  
  <p>Please suggest how to resolve this ?</p>
  
  <p>My devicethread &amp; worker object defined in Mainwindow class :--   </p>
  
  <pre><code>QThread m_deviceThread;
  deviceThreadObject *m_deviceThreadObject;
  </code></pre>
  
  <p>Main device thread object :-----</p>
  
  <pre><code>class deviceThreadObject : public QObject
  {
      Q_OBJECT
  public:
      explicit deviceThreadObject(QObject *parent = 0);
  
      /*!
        Termination control main thread
      */
      bool m_bQuit;
  
  
  signals:
  
  public slots:
      void dowork();
  
  };
  </code></pre>
  
  <p>deviceThreadObject object constructor :--</p>
  
  <pre><code>// constructor for the deviceThreadObject
  deviceThreadObject::deviceThreadObject(QObject *parent) :
      QObject(parent)
  {
      m_bQuit = false;
  }
  </code></pre>
  
  <p>I have main thread <code>m_deviceThread</code> which runs on button start pressed:---</p>
  
  <pre><code>void MainWindow::on_actionStart_triggered()
  {
      if(!b_threadAlreadyStarted)
      {
  
     m_deviceThreadObject = new deviceThreadObject;
  
      // connect device thread signal to the slot
      connect(&amp;m_deviceThread ,SIGNAL(started()),m_deviceThreadObject,SLOT(dowork()));
  
      m_deviceThreadObject-&gt;moveToThread(&amp;m_deviceThread);
  
      // Set the flag before starting slot of main thread
      m_deviceThreadObject-&gt;m_bQuit = true;
  
      m_deviceThread.start();
  
      }
  }
  </code></pre>
  
  <p>I have main thread <code>m_deviceThread</code> which stops on button stop pressed:---</p>
  
  <pre><code>void MainWindow::on_actionStop_triggered()
  {
      if(b_threadAlreadyStarted)
      {
  
          b_threadAlreadyStarted = false;
  
          // get out of event loop
          m_deviceThreadObject-&gt;m_bQuit = false;
  
          m_deviceThread.quit();
          qDebug() &lt;&lt; " \n quit ";
  
          // wait for thread to terminate
          while(!m_deviceThread.wait());
  
          m_deviceThreadObject-&gt;deleteLater();
  
          qDebug() &lt;&lt; " \n finished";
  
      }
  
  }
  </code></pre>
  
  <p>// Common slot for the Device - thread</p>
  
  <pre><code>void deviceThreadObject::dowork()
  {
  
    while(m_bquit)
    {
  
       // Do some work
  
    }
  
  }
  </code></pre>