Qt线程--降低线程占用CPU

问题描述

一般将计算量大的处理过程单独放置到一个单独的线程处理,因此很有可能你的处理过程需要while(1)或类似的操作。也因此很有可能造成线程在处理时计算机CPU占用过高的情况。

解决办法

  • 降低相应线程优先级
  • sleep

具体实现

    1.创建工作线程

#include <QThread>
#include <QDebug>
#include <QMutex>
#include <QMutexLocker>

#include <unistd.h>

class WorkThread : public QThread
{
    Q_OBJECT
public:
    explicit WorkThread(QObject *parent = 0):
        QThread(parent)
      ,m_bStop(false)
      ,m_iTest(0)
    {}

    ~WorkThread()
    {
        wait();
    }

    void stop()
    {
        QMutexLocker Locker(&m_mutexLock);
        m_bStop = true;
    }

protected:
    void run()
    {
        do{
            m_iTest++;
            emit sigFind(QString::number(m_iTest));
            sleep(10);//::sleep(10);
        }while(!m_bStop);
    }

signals:
    void sigFind(const QString &);

private:
    bool m_bStop;
    int m_iTest;
    QMutex m_mutexLock;
};

 

    2.创建工作对象

#include <QObject>
#include <QDateTime>
#include <QTimerEvent>
#include <QCoreApplication>

#include "workthread.hpp"

class WorkObject : public QObject
{
    Q_OBJECT

private:
    int m_iTimerId_PrintTime;
    WorkThread *m_threadWork;

public:
    explicit WorkObject(QObject *parent = 0):
        QObject(parent)
      ,m_iTimerId_PrintTime(-1)
      ,m_threadWork(0)
    {
        //Timer
        m_iTimerId_PrintTime = startTimer(1000);//print current time: yyyy-MM-dd hh:mm:ss

        // WorkThread
        m_threadWork = new WorkThread(this);
        connect(m_threadWork,SIGNAL(sigFind(QString)),this,SLOT(slotFind(QString)));
        connect(m_threadWork,SIGNAL(finished()),m_threadWork,SLOT(deleteLater()));

        m_threadWork->start();
    }

    ~WorkObject()
    {
        if(m_threadWork)
            m_threadWork->stop();
    }

protected:
    void timerEvent(QTimerEvent *event)
    {
        if(event->timerId() == m_iTimerId_PrintTime)
        {
            qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        }
    }

    
private slots:
    void slotFind(const QString &s)
    {
        qDebug()<<"Find:"<<s;
    }
};

 

    3.main.cpp

#include <QTimer>
#include <QtCore/QCoreApplication>

#include "workobject.hpp"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    WorkObject worker;

    QTimer::singleShot(10000, &a, SLOT(quit()));
    return a.exec();
}

 

    4.执行结果

  

最后

sleep会降低速度...所以测试一下,使用较低优先级或许就可以满足您的要求了呢~~

posted @ 2016-09-08 22:57  GoMountains  阅读(2925)  评论(0编辑  收藏  举报