gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:57:35 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com