以前看過在linux下C編程的線程書籍,今天來看看Qt如何啓動一個線程吧,代碼就以精通Qt4編程的爲例
先來給出每個文件的相關代碼然後再加以分析
//*************dialog.h**************//
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#define MAXSIZE 5 //最大的線程數
class QDialogButtonBox;
class QProgressBar;
class QPushButton;
class WorkThread;
class ThreadDlg : public QDialog
{
Q_OBJECT
public:
ThreadDlg(QWidget *parent = 0);
public slots:
void start();
void stop();
private:
QPushButton *startButton;
QPushButton *quitButton;
QPushButton *stopButton;
QDialogButtonBox *buttonBox;
WorkThread* threadVector[MAXSIZE];
};
#endif
//***********end end end************//
//***********mainwindow.h************//
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QThread>
class WorkThread : public QThread
{
protected:
void run(); //重新實現run()函數
};
#endif
//***********end end end************//
//***********dialog.cpp************//
#include <QtGui>
#include "workThread.h"
#include "dialog.h"
ThreadDlg::ThreadDlg(QWidget *parent)
: QDialog(parent)
{
startButton = new QPushButton(tr("開始"));
quitButton = new QPushButton(tr("退出"));
stopButton = new QPushButton(tr("停止"));
stopButton->setEnabled(false);
buttonBox = new QDialogButtonBox;
buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(stopButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
connect(startButton, SIGNAL(clicked()), this, SLOT(start()));
connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
connect(stopButton, SIGNAL(clicked()), this, SLOT(stop()));
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setWindowTitle(tr("啓動線程"));
}
void ThreadDlg::start()
{
for(int i=0;i<MAXSIZE;i++)
{
threadVector[i] = new WorkThread(); //創建線程
}
for(int i=0;i<MAXSIZE;i++)
{
threadVector[i]->start(QThread::LowestPriority); //啓動線程同時設置它的優先級,當然也可以不帶,使用默認的優先級
}
stopButton->setEnabled(true);
startButton->setEnabled(false);
}
void ThreadDlg::stop()
{
for(int i=0;i<MAXSIZE;i++)
{
threadVector[i]->terminate(); //終止線程
threadVector[i]->wait(); //阻塞等待
}
startButton->setEnabled(true);
stopButton->setEnabled(false);
}
//***********end end end************//
//***********mainwindow.cpp************//
#include "workThread.h"
#include "dialog.h"
#include <QTextEdit>
#include <QDebug>
#include <stdio.h>
void WorkThread::run()
{
while(true)
for (int n = 0; n < 10;++n) {
printf("%d/n",n); //打印輸出
}
}
//***********end end end************//
//***********main.cpp************//
#include <QApplication>
#include <QtCore>
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForTr( QTextCodec::codecForName("gb2312"));
ThreadDlg dialog;
dialog.show();
return dialog.exec();
}
//***********end end end************//
以上代碼簡單,沒有必要做過多的講解,但是其中的“threadVector[i]->terminate(); ”有必要講解下,terminate()函數的調用便不會立刻終止線程,因爲線程的何時終止取決於系統的調度策略,所在在之後又調用了wait()函數是的線程阻塞等待直到退出或者超時。
最後加以一點就是在.pro文件中加入一行代碼才能成功運行:
CONFIG+=thread