一、前言
在我很久之前的文章【学习QT之多线程编程两种方式详解】中,已经论述过Qt中使用线程的两中方式了。
在子线程中,我们往往希望它干一些费时的任务,所以经常会需要使用死循环。也许你会想到如下写法:
或者是
- 方法1:倾向于单片机死循环的写法,但是这种写法实测是无法关闭线程的,使用
stop()
、exit()
都无法关闭线程; - 方法2:使用标志变量,我们可以通过改变标志变量的状态,来控制子线程任务的执行,这个方法比方法1要好一点,但是也无法精准的控制子线程
二、官方推荐方法
- 采用
isInterruptionRequested()
方法控制线程是否停止,该方法只有qt5才具备; - 采用锁
m_mutex
来决定线程是否暂停。 - 用一个while循环使子线程一直处于运行状态。
- 如果该线程上运行的任务应该停止,则返回true。可以通过
requestinterrupt()
请求中断。
线程类
主类调用线程类