首页 > 代码库 > Qt线程(4) 降低线程占用CPU

Qt线程(4) 降低线程占用CPU

  • 问题描述:

    一般将计算量大的处理过程单独放置到一个单独的线程处理,因此很有可能你的处理过程需要while(1)或类似的操作。

  也因此很有可能造成线程在处理时计算机CPU占用过高的情况。

  • 解决办法:
    • 降低相应线程优先级
    • sleep
  • 具体实现:

    1.创建工作线程

技术分享
 1 #include <QThread> 2 #include <QDebug> 3 #include <QMutex> 4 #include <QMutexLocker> 5  6 #include <unistd.h> 7  8 class WorkThread : public QThread 9 {10     Q_OBJECT11 public:12     explicit WorkThread(QObject *parent = 0):13         QThread(parent)14       ,m_bStop(false)15       ,m_iTest(0)16     {}17 18     ~WorkThread()19     {20         wait();21     }22 23     void stop()24     {25         QMutexLocker Locker(&m_mutexLock);26         m_bStop = true;27     }28 29 protected:30     void run()31     {32         do{33             m_iTest++;34             emit sigFind(QString::number(m_iTest));35             sleep(10);//::sleep(10);36         }while(!m_bStop);37     }38 39 signals:40     void sigFind(const QString &);41 42 private:43     bool m_bStop;44     int m_iTest;45     QMutex m_mutexLock;46 };
View Code

    2.创建工作对象

技术分享
 1 #include <QObject> 2 #include <QDateTime> 3 #include <QTimerEvent> 4 #include <QCoreApplication> 5  6 #include "workthread.hpp" 7  8 class WorkObject : public QObject 9 {10     Q_OBJECT11 12 private:13     int m_iTimerId_PrintTime;14     WorkThread *m_threadWork;15 16 public:17     explicit WorkObject(QObject *parent = 0):18         QObject(parent)19       ,m_iTimerId_PrintTime(-1)20       ,m_threadWork(0)21     {22         //Timer23         m_iTimerId_PrintTime = startTimer(1000);//print current time: yyyy-MM-dd hh:mm:ss24 25         // WorkThread26         m_threadWork = new WorkThread(this);27         connect(m_threadWork,SIGNAL(sigFind(QString)),this,SLOT(slotFind(QString)));28         connect(m_threadWork,SIGNAL(finished()),m_threadWork,SLOT(deleteLater()));29 30         m_threadWork->start();31     }32 33     ~WorkObject()34     {35         if(m_threadWork)36             m_threadWork->stop();37     }38 39 protected:40     void timerEvent(QTimerEvent *event)41     {42         if(event->timerId() == m_iTimerId_PrintTime)43         {44             qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");45         }46     }47 48     49 private slots:50     void slotFind(const QString &s)51     {52         qDebug()<<"Find:"<<s;53     }54 };
View Code

    3.main.cpp

技术分享
 1 #include <QTimer> 2 #include <QtCore/QCoreApplication> 3  4 #include "workobject.hpp" 5  6 int main(int argc, char *argv[]) 7 { 8     QCoreApplication a(argc, argv); 9     WorkObject worker;10 11     QTimer::singleShot(10000, &a, SLOT(quit()));12     return a.exec();13 }
View Code

    4.执行结果

  技术分享

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

Qt线程(4) 降低线程占用CPU