gpt4 book ai didi

qt - 如何停止线程 - Qthread

转载 作者:行者123 更新时间:2023-12-02 17:01:07 24 4
gpt4 key购买 nike

我必须在按下两个不同的按钮时启动/停止线程。
请指出我的代码是否正确。我是否错过了 connect() 调用中的某些内容?

问题我面临的是,在我的线程上调用 quit() 后,然后我等待我的线程完成,但线程上的 wait() 调用永远不会返回 true,并且我的程序卡在,while(!m_deviceThread.wait())

请建议如何解决这个问题?

我的设备线程和工作对象在 Mainwindow 类中定义:--

QThread m_deviceThread;
deviceThreadObject *m_deviceThreadObject;

主设备线程对象:-----

class deviceThreadObject : public QObject
{
Q_OBJECT
public:
explicit deviceThreadObject(QObject *parent = 0);

/*!
Termination control main thread
*/
bool m_bQuit;


signals:

public slots:
void dowork();

};

deviceThreadObject 对象构造函数:--

// constructor for the deviceThreadObject
deviceThreadObject::deviceThreadObject(QObject *parent) :
QObject(parent)
{
m_bQuit = false;
}

我有主线程m_deviceThread,它在按下按钮开始时运行:---

void MainWindow::on_actionStart_triggered()
{
if(!b_threadAlreadyStarted)
{

m_deviceThreadObject = new deviceThreadObject;

// connect device thread signal to the slot
connect(&m_deviceThread ,SIGNAL(started()),m_deviceThreadObject,SLOT(dowork()));

m_deviceThreadObject->moveToThread(&m_deviceThread);

// Set the flag before starting slot of main thread
m_deviceThreadObject->m_bQuit = true;

m_deviceThread.start();

}
}

我有主线程m_deviceThread,它在按下停止按钮时停止:---

void MainWindow::on_actionStop_triggered()
{
if(b_threadAlreadyStarted)
{

b_threadAlreadyStarted = false;

// get out of event loop
m_deviceThreadObject->m_bQuit = false;

m_deviceThread.quit();
qDebug() << " \n quit ";

// wait for thread to terminate
while(!m_deviceThread.wait());

m_deviceThreadObject->deleteLater();

qDebug() << " \n finished";

}

}

//设备的公共(public)槽 - 线程

void deviceThreadObject::dowork()
{

while(m_bquit)
{

// Do some work

}

}

最佳答案

我过去见过几种不同的方法来做到这一点。

下面显示了编译器优化代码的样子:

bool quit = false;
while(!quit)
{
// no reference to quit here or in any functions mentioned in here
}

可能会变成一个永远循环。

// bool quit = false
while(true)
{
// looks the same to the compiler...
}

迫使您了解线程同步和关键区域或互斥体或信号量的最佳实践是将对 quit 参数的访问视为线程之间共享的变量,并将其包装起来,以便仅由一个线程在某一时刻访问它。时间。我的首选方法是使用 QMutexLocker,因为它可以很好地处理范围更改、返回、中断等。

http://qt-project.org/doc/qt-5.1/qtcore/qmutexlocker.html#details

因此您的代码会添加如下内容:

deviceThreadObject::deviceThreadObject(QObject *parent) :
QObject(parent)
{
m_mutex = new QMutex();
}

void deviceThreadObject::stop()
{
QMutexLocker locker(m_mutex);
m_stopped = true;
}

void deviceThreadObject::doWork()
{
m_stopped = false;
while(true)
{
// The core work of your thread...

// Check to see if we were stopped
{
QMutexLocker locker(m_mutex);
if(m_stopped)
break;
}// locker goes out of scope and releases the mutex
}
}

一个快速但肮脏的捷径是使用 volatile bool 。这不是推荐的做法,并且在跨编译器上并不可靠。

希望有帮助。

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

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