Advertisement

qt 销毁线程处理

阅读量:

基本思路:

当主线程需要销毁子线程时 使用bool变量 来使run函数退出

当 run 完成后, 线程随后也会终止触发 ended 事件, 此时我们执行 deleteLater 函数来销毁申请的内存占用的空间.

同时将主线程实例化对象的指针释放掉,以便于后续还需要创建该线程

1 主线程的操作

复制代码
 //主线程 实例化一个类

    
  
    
 pthreat = new threat();
    
     QObject::connect(pthreat ,&QThread::finished ,pthreat ,&QObject::deleteLater);
    
  
    
 pthreat ->Start();

2 子线程类说明 .h文件

复制代码
 class threat: public QThread

    
 {
    
     Q_OBJECT
    
 public:
    
     threat(QString s,Log *l);
    
     ~threat();
    
     void Start();
    
     void Stop();
    
 private:
    
     volatile bool Stopthread;
    
  
    
 protected:
    
     void run();
    
 };

子线程类说明 .cpp文件

复制代码
  
    
 threat::threat()
    
 {
    
     Stopthread = false;
    
 }
    
  
    
 void threat::run()
    
 {
    
  
    
     while(!Stopthread)
    
     {
    
     //业务代码
    
     }
    
 }
    
 void threat::Start()
    
 {
    
     this->start();
    
     this->quit();
    
     this->wait()
    
  
    
 }
    
 void threat::Stop()
    
 {
    
     Stopthread = true;
    
 }
复制代码
 void zhuxiancheng::destorypthreat()

    
 {
    
     if(nullptr != pthreat )
    
     {
    
     pthreat ->Stop();
    
     delete pthreat ;
    
     pthreat = nullptr;
    
     }
    
 }

参考资料:

该文详细介绍了如何使用Qt工具创建并终止线程的技术方法

QT5线程关闭 - 个人网站 - 研究者博客

全部评论 (0)

还没有任何评论哟~