QThread安全的結束線程


博客地址已更改,文章數量較多不便批量修改,若想訪問源文請到 coologic博客 查閱,網址:www.coologic.cn

如本文記錄地址為 techieliang.com/A/B/C/ 請改為 www.coologic.cn/A/B/C/ 即可查閱

 

版權聲明:若無來源注明, Techie亮博客文章均為原創。 轉載請以鏈接形式標明本文標題和地址:
本文標題:QThread安全的結束線程     本文地址: http://techieliang.com/2017/12/599/

1. QThread使用

基本使用請見:http://techieliang.com/2017/12/592/

在上文中提到了一個簡單范例:

  1. #include <QCoreApplication>
  2. #include <QThread>
  3. #include <QDebug>
  4. class MyThread : public QThread {
  5. protected:
  6. void run() {
  7. while(1) {
  8. qDebug()<<"thread start:"<<QThread::currentThreadId();
  9. msleep(500);
  10. }
  11. }
  12. };
  13. int main(int argc, char *argv[]) {
  14. QCoreApplication a(argc, argv);
  15. qDebug()<<"Main:"<<QThread::currentThreadId();
  16. MyThread m;
  17. m.start();
  18. QThread::sleep(5);
  19. m.terminate();
  20. m.wait();
  21. return 0;
  22. }

此范例使用terminate強制關閉線程,此行為是很危險的,下面提供一種安全的關閉方式

  1. #include <QCoreApplication>
  2. #include <QThread>
  3. #include <QDebug>
  4. class MyThread : public QThread {
  5. public:
  6. void stop() { //用於結束線程
  7. is_runnable =false;
  8. }
  9. protected:
  10. void run() {
  11. while(is_runnable) {
  12. qDebug()<<"thread start:"<<QThread::currentThreadId();
  13. msleep(500);
  14. }
  15. is_runnable = true;
  16. }
  17. private:
  18. bool is_runnable = true; //是否可以運行
  19. };
  20. int main(int argc, char *argv[]) {
  21. QCoreApplication a(argc, argv);
  22. qDebug()<<"Main:"<<QThread::currentThreadId();
  23. MyThread m;
  24. m.start();
  25. QThread::sleep(5);
  26. m.stop();
  27. m.wait();
  28. return 0;
  29. }

通過對while循環增加bool類型作為判斷實現安全的結束線程,當is_runnable=false時,程序會完成此次循環后結束,所以要wait等待,不可直接關閉程序。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM