1.多线程的简单实现

        <1> 在头文件threaddlg.h声明用于界面显示所需的控件,其代码如下:

#ifndef THREADDLG_H
#define THREADDLG_H

#include <QDialog>
#include <QPushButton>
#include "workthread.h"
#define MAXSIZE 5

class ThreadDlg : public QDialog
{
    Q_OBJECT
    
public:
    ThreadDlg(QWidget *parent = 0);
    ~ThreadDlg();    
private:
    QPushButton *startBtn;
    QPushButton *stopBtn;
    QPushButton *quitBtn;
public slots:
    void slotStart();
    void slotStop();
private:
    WorkThread *workThread[MAXSIZE];
};

#endif // THREADDLG_H

         <2> 在源文件“threaddlg.cpp的构造函数中,完成各个控件的初始化工作其具体代码如下:

#include "threaddlg.h"
#include <QHBoxLayout>

ThreadDlg::ThreadDlg(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(tr("线程"));

    startBtn = new QPushButton(tr("开始"));
    stopBtn = new QPushButton(tr("停止"));
    quitBtn = new QPushButton(tr("退出"));

    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->addWidget(startBtn);
    mainLayout->addWidget(stopBtn);
    mainLayout->addWidget(quitBtn);

    connect(startBtn,SIGNAL(clicked()),this,SLOT(slotStart()));
    connect(stopBtn,SIGNAL(clicked()),this,SLOT(slotStop()));
    connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));
}

ThreadDlg::~ThreadDlg()
{
    
}

void ThreadDlg::slotStart()
{
    for(int i=0;i<MAXSIZE;i++)
    {
        workThread[i]=new WorkThread();
    }
    for(int i=0;i<MAXSIZE;i++)
    {
        workThread[i]->start();
    }
    startBtn->setEnabled(false);
    stopBtn->setEnabled(true);
}

void ThreadDlg::slotStop()
{
    for(int i=0;i<MAXSIZE;i++)
    {
        workThread[i]->terminate();
        workThread[i]->wait();
    }
    startBtn->setEnabled(true);
    stopBtn->setEnabled(false);
}

        <3> 以上完成了界面的设计及调用线程实例,下面的内容是具体的功能实现。

        <3-1>在头文件“workthread.h”中,工作线程WorkThread类继承自QThreao类。重新实现run()函数。其具体代码如下:

#ifndef WORKTHREAD_H
#define WORKTHREAD_H

#include <QThread>

class WorkThread : public QThread
{
    Q_OBJECT
public:
    WorkThread();
protected:
    void run();
};

#endif // WORKTHREAD_H

        <3-2> 在源文件“workthread.cpp”中添加具体实现代码如下:

#include "workthread.h"
#include <QtDebug>

WorkThread::WorkThread()
{
}

void WorkThread::run()
{
    while(true)
    {
        for(int n=0;n<10;n++)
            qDebug()<<n<<n<<n<<n<<n<<n<<n<<n;
    }
}

<4> main.cpp中代码实现

#include "threaddlg.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ThreadDlg w;
    w.show();
    
    return a.exec();
}

<5> 运行效果,如下所示:

Qt5多线程<12>-LMLPHP

Qt5多线程<12>-LMLPHP

2.多线程的控制

        多线程控制可通过互斥量和信号量。

2.1 互斥量

       为了防止多个线程对同一个资源进行访问,Qt中加入互斥量,互斥量可以通过QMutex或者QMutexLocker

11-10 10:28