线程
QT中的QThread提供了与平台无关的线程,一个QThread代表了一个应用程序中可用独立控制的线程,它与进程中的其他线程共享数据,但是是独立执行的,QThread从run()函数开始执行,默认run()通过exec()来开启事件循环,并在线程内运行一个Qt事件循环。
要创建一个线程,需要继承自QThread,并重新实现run()函数。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #ifndef MYTHREAD_H #define MYTHREAD_H
#include <QThread>
class MyThread : public QThread { Q_OBJECT public: MyThread(QObject* parent = nullptr);
void stop();
protected:
void run() override;
private: bool m_isStopped; };
#endif
#include "widget.h" #include "ui_widget.h"
extern int gPies;
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); }
Widget::~Widget() { delete ui; }
void Widget::on_startBtn_clicked() { gPies = 0; m_MyThread1.start(); }
void Widget::on_stopBtn_clicked() { m_MyThread1.stop(); }
|
当多个同类型的线程执行时,有可能发生数据错误。
也就是说,
多线程并发执行的时候,共享数据的准确性是不确定的。
QMutex提供了一个互斥锁(mutex),在任何时间至多有一个线程可以获得mutex,如果一个线程尝试获得mutex,而mutex此时已被锁住,则这个线程会睡眠,直到现在获得mutex的线程对mutex解锁为止。互斥锁常用于对共享数据的访问进行保护。
示例:
1 2 3 4 5 6 7 8 9
| void MyThread::run() { int i = 0 ; while(!m_isStopped && i++ < 200){ mutex.lock(); qDebug()<<QString("掉了%1个大饼").arg(++gPies); mutex.unlock(); } }
|