QT Qthread中止回收

在QT开辟一个QThrea线程时,想要中止并且回收资源,一般这样写:
//退出线程
recThread->quit();
//回收资源
recThread->wait();
delete reciveImageThread;

上面reciveImageThread是自定义的线程类,recThread是QThread类
但在实际操作中,我们在运行一个子线程时,有可能是一个while(1)循环,此时子线程会阻塞在wait()中不能跳出来,这样就无法正常关闭子线程。
一个比较极端的做法是,调用void QThread::terminate(),terminate()会强制中断子线程,但这是比较危险的做法。下面是QT官方的说法:
This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
所以实际操作中,不推荐使用terminate()。

下面推荐一个实际操作中比较好用的做法,设置标志位。
在线程进入while循环时,设置标志位flag,flag为true时才进入循环。平常我们需要子线程运行时,flag置为true,在我们要关闭子线程时,将flag置为false。
//标志
flag = false;
//退出线程
recThread->quit();
//回收资源
recThread->wait();
delete reciveImageThread;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值