停止线程的方法是什么(当我直接继承QThread的时候)?
What is the way to stop the thread (when I directly inherit from QThread)?
.h
#include <QThread>
#include <QDebug>
class MainWindow : public QThread
{
Q_OBJECT
protected:
void run()
{
while (1)
{
qDebug() << "\nsdfdsf";
}
}
public:
MainWindow(QThread *parent = 0);
~MainWindow();
};
.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QThread *parent)
: QThread(parent)
{
start();
}
MainWindow::~MainWindow()
{
}
现在,我知道这是使用线程的旧方法。
我想知道在使用方法时停止线程的方法是什么?
请举例说明。
在Qt5中,有interrupt request (QThread::requestInterruption
)线程可以处理,所以有一种优雅统一的方式让线程停止。
另见 this answer。
最简单的方法是将 while(1)
替换为 while(someCondition)
,其中 someCondition
可能代表一个简单的布尔变量、您调用的函数或任何其他检查是否适合确定线程应该还是运行。
.h
#include <QThread>
#include <QDebug>
class MainWindow : public QThread
{
Q_OBJECT
protected:
void run()
{
while (1)
{
qDebug() << "\nsdfdsf";
}
}
public:
MainWindow(QThread *parent = 0);
~MainWindow();
};
.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QThread *parent)
: QThread(parent)
{
start();
}
MainWindow::~MainWindow()
{
}
现在,我知道这是使用线程的旧方法。 我想知道在使用方法时停止线程的方法是什么?
请举例说明。
在Qt5中,有interrupt request (QThread::requestInterruption
)线程可以处理,所以有一种优雅统一的方式让线程停止。
另见 this answer。
最简单的方法是将 while(1)
替换为 while(someCondition)
,其中 someCondition
可能代表一个简单的布尔变量、您调用的函数或任何其他检查是否适合确定线程应该还是运行。