QT多线程使用


QThread

继承QThread类构建线程,可以使用信号槽通信

class Thread : public QThread
{
	Q_OBJECT
publicvoid 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); //用来监视函数结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆不凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值