簡體   English   中英

如何停止循環線程

[英]How to stop looping thread

我想在發出信號時停止循環線程,所以這是我的代碼

void  MyThread::stopWatchingThread()
{
    qDebug()<<"MyThread::stopWatchingThread()";    
    Keep_running=false;
    qDebug()<<"MyThread::stopWatchingThread Keep_running"<<Keep_running;
    ...
}

void MyThread::run()
{
  qDebug()<<"MyThread::run()";
  qDebug()<<"MyThread::run Keep_running"<<Keep_running;  
  while(Keep_running)
    {
     ...
     }
  qDebug()<<"MyThread::run Keep_running"<<Keep_running;
  Keep_running=false;
  qDebug()<<"MyThread::run Keep_running"<<Keep_running;
}

void Watcher::Init()
{
    WatchingThread=new MyThread(this->L_RootToWatch);
    connect(this,SIGNAL(stopmonotiring()),WatchingThread, SLOT(stopWatchingThread()));
...
}
void Watcher::StartWatching()
{
    WatchingThread->start();
}

void Watcher::StopWatching()
{
    emit stopmonotiring();        
}

所以每件事情都可以,但我的問題是Keep_running在發出stopWatchingThread之后永遠不會在MyThread::run()得到false值,所以while循環永遠。 我錯過了什么 ? 任何幫助將不勝感激。

不要在Qt中顯式創建線程類。 相反,創建一個工作對象,將該對象移動到QThread ,然后在QThread上調用start() 這是一個簡單的例子:

class Worker : public QObject
{
  Q_OBJECT
public:
  Worker( QObject * parent = 0 )
    : QObject( parent )
  {}

public slots:
  void doWork( ... )
  { 
    // do work here
  }

  void stopMonitoring()
  { 
    emit finished();
  }

signals:
  void finished();
};

int main()
{
  Worker * w = new Worker();
  QThread * thread = new QThread();
  QObject::connect( w, SIGNAL(finished()), thread, SLOT(quit())
  QObject::connect( w, SIGNAL(finished()), w, SLOT(deleteLater())
  QObject::connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater())
  w->moveToThread( thread );
  thread->start();

  // some other object emits a signal connected to the 'doWork()' slot.
}

我省略了一些標准的QApplication樣板,但如果你使用的是Qt,你已經有了。 這應該讓你開始。

由於您的run()方法阻塞且事件循環從未進入,因此永遠不會調用slot stopWatchingThread。 您必須調用exec(),而不是通過run()中的旋轉循環來阻止事件循環。 要么是這樣,要么讓觀察者線程直接調用stopWatchingThread而不是使用信號/插槽連接。 我會選擇后者。 keepRunning將從多個線程訪問,因此您必須使用QMutex,QReadWriteLock或QAtomic保護它。 (從QMutex開始,這是最簡單的)。

如果在線程中使用事件循環,只需將quit()信號發布到線程對象。

也許你的C ++編譯器優化了Keep_running上的讀操作。 嘗試將其聲明為volatile ,它告訴編譯器此變量可能會“意外地”更改,例如來自其他線程或硬件中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM