c++ - 如何停止循环线程

标签 c++ qt qthread

我想在发出信号时停止循环线程,所以这是我的代码

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永远得不到false MyThread::run() 中的值发射后 stopWatchingThread所以 while永远循环。 我错过了什么 ? 任何帮助将不胜感激。

最佳答案

不要在 Qt 中显式创建线程类。相反,创建一个 worker 对象,将该对象移动到 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,那么您已经拥有了。这应该可以帮助您入门。

关于c++ - 如何停止循环线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14475380/

相关文章:

c++ - 需要一些清晰的模板实现代码

c++ - GetAsyncKeyState 使我的程序在打开时崩溃

c++ - 如何在不使用数组的情况下存储输入?

c++ - 如何正确使用 qt 的信号/插槽系统

python - 计时器无法从另一个线程停止 - 删除焦点

c++ - QNetworkAccessManager 即使在另一个线程中也会卡住 GUI

如果弹出空队列,C++ 抛出异常

qt - 断开插槽与信号的连接

c++ - 读取 http 请求 header (Qt/c++)

c++ - Qt 终止由 QConcurrent::run 生成的线程