QT多线程
2014年11月18日
注意:exec()将启动消息循环,并阻塞,直到exit()被主动调用。期间会一直保持running状态。如果只是调用工作函数,完成后返回,则不需要调用exec()。
1) 启动线程:start()。调用run()开始线程工作。
2) 结束线程:当从run()返回时,正常结束线程。如果使用terminate(),有可能造成危险(无法执行清理),尽量避免使用;如果使用,则应该使用wait()配合来等待结束。setTerminateEnabled()可以设置能否强行中止。
3) 工作函数:run(),默认情况下会调用exec()启动消息循环。实际的工作在此函数中实现。从此函数返回,将结束线程。如果只是完成工作并返回,则不需要启动exec()。
4) 生成自定义线程:继承QThread,然后重写run()。在run()中调用exec()启动消息循环。对于moveToThread()的操作方法,灵活性高,但是设置也相对复杂,不推荐。参考(http://www.it558.com/plus/view.php?aid=7987)
5) 线程状态:使用信号started(),finished(),terminated()。或者使用isRunning(),isFinished()来查询。
6) 等待线程结束:wait()。
7) 设置线程睡眠:sleep(s),msleep(ms),usleep(microsecond)。
8) 消息循环:exec()启动,quit()/exit()结束。
9) 设置线程的栈大小: setStackSize(),默认使用系统定义大小,可以设置。
10) 获取线程ID:currentThreadId(),不同平台不同表示方法。
11) 获取线程指针(也可作为ID):currentThread()。
12) 最优线程数:idealThreadCount(),当前的CPU核心数(如果无法检测,则返回-1)。
13) 优先级:priority(),如果不在运行状态,则返回InheritPriority。setPriority(),设置优先级。
14) 让出CPU:yieldCurrentThread()。OS决定由哪个线程接手。
//qmythread.h
#ifndefQMYTHREAD_H
#defineQMYTHREAD_H
#include<QThread>
classQMyThread:publicQThread
{
Q_OBJECT
public:
explicitQMyThread(QObject*parent=0,intiIndex=0);
public://run
voidrun();
signals:
publicslots:
private:
intm_iIndex;
};
#endif//QMYTHREAD_H
//qmythread.cpp
#include"qmythread.h"
#include<iostream>
QMyThread::QMyThread(QObject*parent,intiIndex):
QThread(parent)
,m_iIndex(iIndex)
{
}
voidQMyThread::run()
{
for(inti=0;i<10;i++)
{
sleep(1);
std::cout<<m_iIndex<<":"<<i<<std::endl;
}
exec();
}
//main.cpp
#include"ui/qtcmdcore.h"
#include"ui/mainwindow.h"
#include<QApplication>
#include"qmythread.h"
#include<iostream>
intmain(intargc,char*argv[])
{
QApplicationa(argc,argv);
//determineopentype
if(argc>1)//cmdtype
{
gutang::cmdcore::QtCmdCore::parseCmd(argc,argv);
return0;
}
QVector<QMyThread*>vThread;
QMyThreadt0(NULL,0);
QMyThreadt1(NULL,1);
QMyThreadt2(NULL,2);
vThread<<&t0<<&t1<<&t2;
for(inti=0;i<3;++i)
{
vThread[i]->start();
std::cout<<"thread"<<i<<"isstarting..."<<std::endl;
}
t0.wait();
t1.wait();
t2.wait();
returna.exec();
}