【QT】73.QT中的多线程编程

class Mythread : public QThread
{
 protected:
     void run()  //线程入口函数
     {
         for(int i=0; i<5; i++)
         {
             qDebug() << objectname{} <<" : "  << i;
             sleep(1);     // Qthread 的静态成员函数      
         }
     }
};

int main(int argc, char* argv[])
{
    qDebug() << "Main begin";
    Mythread d;
    d.setObjectname("t");
    d.start();
    
    qDebug() << "Main end";
}

//输出
main begin
Main end
"t": 0;
"t": 1;
"t": 2;
"t": 3;
"t": 4;

线程是并行运行的(上面主线程优于子线程结束)

一个进程等到所有线程结束之后在结束

自然死亡;非自然死亡(调用函数terminate())

 

如何在代码中如何优雅的终止线程??

 

// 优雅安全退出进程,模型,适用于任何多线程编程

class Solution : public QThread
{
   protected:
       volatile bool m_toStop;
   public:
       Solution()
       {
           m_toStop = false;
       }   
       void stop()
       {
           m_toStop = true;
       } 
};

void Solution::run()
{
    while(!m_tostop)
    {
        // do task
    }
}

 

注:本笔记根据狄泰软件学院课程做的

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值