QThread
继承QThread类构建线程,可以使用信号槽通信
class Thread : public QThread
{
Q_OBJECT
public:
void setStop();
protected:
void run();
signals:
void sgl_SendMsg(); //自己的信号,可在线程进行中发送消息
private:
bool m_isStopped; //保证线程正常结束
};
void Thread::run()
{
while(!m_isStopped)
{
//主体
}
m_isStopped = false;
}
void Thread::setStop()
{
m_isStopped = true;
}
QThreadPool
Qt的线程池
You may need to create and destroy threads frequently, as managing QThread instances by hand can become cumbersome. For this, you can use the QThreadPool class, which manages a pool of reusable QThreads.
——《Mastring Qt5》
*可通过继承QObject发送信号等。
#include <QCoreApplication>
#include <QObject>
#include <QRunnable>
#include <QThread>
#include <QThreadPool>
#include <QDebug>
class HelloWorldTask : public QRunnable
{
// 线程执行任务:每间隔10s打印出线程的信息
void run()
{
qDebug() << QThread::currentThread();
QThread::msleep(10000);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThreadPool::globalInstance()->setMaxThreadCount(8);
for (int nNum = 0; nNum < 100; nNum++)
{
HelloWorldTask *task = new HelloWorldTask;
QThreadPool::globalInstance()->start(task);
}
return a.exec();
}
Qt Concurrent
Another approach to multi-threaded development is available with the Qt Concurrent framework. It is a higher-level API that avoids the use of mutexes/lock/wait conditions and promotes the distribution of the processing among CPU cores.
——《Mastring Qt5》
函数级别的多线程。当界面操作比较费时时,可使用Qt Concurrent将逻辑放在新线程中防止界面卡顿。
QFutureWatcher<void> watcher;
void longRunningFunction();
QFuture<void> future; //QFuture 用来返回QtConcurrent::run()的执行结果
future = QtConcurrent::run(longRunningFunction); //将会在默认的线程池中获取一个线程来执行函数函数longRunningFunction()
watcher.setFuture(future); //用来监视函数结果