1. QThread使用
基本使用请见:http://techieliang.com/2017/12/592/安全
在上文中提到了一个简单范例:app
- #include <QCoreApplication>
- #include <QThread>
- #include <QDebug>
- class MyThread : public QThread {
- protected:
- void run() {
- while(1) {
- qDebug()<<"thread start:"<<QThread::currentThreadId();
- msleep(500);
- }
- }
- };
- int main(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- qDebug()<<"Main:"<<QThread::currentThreadId();
- MyThread m;
- m.start();
- QThread::sleep(5);
- m.terminate();
- m.wait();
- return 0;
- }
此范例使用terminate强制关闭线程,此行为是很危险的,下面提供一种安全的关闭方式spa
- #include <QCoreApplication>
- #include <QThread>
- #include <QDebug>
- class MyThread : public QThread {
- public:
- void stop() { //用于结束线程
- is_runnable =false;
- }
- protected:
- void run() {
- while(is_runnable) {
- qDebug()<<"thread start:"<<QThread::currentThreadId();
- msleep(500);
- }
- is_runnable = true;
- }
- private:
- bool is_runnable = true; //是否能够运行
- };
- int main(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- qDebug()<<"Main:"<<QThread::currentThreadId();
- MyThread m;
- m.start();
- QThread::sleep(5);
- m.stop();
- m.wait();
- return 0;
- }
经过对while循环增长bool类型做为判断实现安全的结束线程,当is_runnable=false时,程序会完成这次循环后结束,因此要wait等待,不可直接关闭程序。线程