深入理解 QThread

来源:互联网 发布:arraylist java 编辑:程序博客网 时间:2024/06/09 02:32

  • 简述
  • 使用
    • 1-0
    • 1-1

简述

run()是线程执行的入口。run()之于QThread,犹如main()至于QApplication。QThread的一个实例在执行完它的start()后,便开始执行run()中的代码。

使用

1-0

派生 QThread 并重写 run() 函数。

#include <QtCore/QCoreApplication>#include <QThread>#include <QDebug>class Thread : public QThread{private:    void run()    {        qDebug() << "From worker thread: " << currentThreadId();    }};int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);    qDebug() << "From main thread: " << QThread::currentThreadId();    Thread t;    t.start();    return a.exec();}

输出结果大致如下:

From main thread:  0x1d5cFrom worker thread:  0x1b3c

1-1

因为QThread::run()是工作线程的入口,所以任何没有在run()直接调用的函数,都不会在工作线程中执行。
如下面的这个例子,m_stop 分别在run()和stop()中被访问,试猜想这两次访问在什么线程中执行呢?

#if QT_VERSION>=0x050000#include <QtWidgets>#else#include <QtGui>#endifclass Thread : public QThread{    Q_OBJECTpublic:    Thread():m_stop(false)    {}public slots:    void stop()    {        qDebug()<<"Thread::stop called from main thread: "<<currentThreadId();        QMutexLocker locker(&m_mutex);        m_stop=true;    }private:    QMutex m_mutex;    bool m_stop;    void run()    {        qDebug()<<"From worker thread: "<<currentThreadId();        while (1) {            {            QMutexLocker locker(&m_mutex);            if (m_stop) break;            }            msleep(10);        }    }};#include "main.moc"int main(int argc, char *argv[]){    QApplication a(argc, argv);    qDebug()<<"From main thread: "<<QThread::currentThreadId();    QPushButton btn("Stop Thread");    Thread t;    QObject::connect(&btn, SIGNAL(clicked()), &t, SLOT(stop()));    QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));    t.start();    btn.show();    return a.exec();}
原创粉丝点击