Qt:多线程中断

来源:互联网 发布:网络兼职哪些是真的吗 编辑:程序博客网 时间:2024/05/18 11:14

线程使用有两种方法,具体介绍见:http://blog.csdn.net/cfqcfqcfqcfqcfq/article/details/51627885;;

关于线程中断的函数:quit()      Exit()     terminate();除此之外比较常用的函数(起到阻塞作用):wait()  sleep()  ;

在线程类被析构的时候,应该习惯性的设置中断和阻塞;避免出现一些不必要的错误;

 

分别在两种线程使用方法中说明这些函数; 第一种引入线程控制类,其中析构函数中设置:

  ~Controller() {          workerThread.quit();          workerThread.wait();      }  
quit函数是中断线程循环,但中断循环不代表当前线程没有被执行,需要接着设置wait()函数,阻塞workerthread被析构直到当前线程中任务执行完毕退出线程。

quit()函数说明:

Tells the thread's event loop to exit with return code 0 (success). Equivalent to calling QThread::exit(0).This function does nothing if the thread does not have an event loop.
quit()函数只是中断线程循环 等效于exit(0);不要放大它的作用;其不能让线程立即停止。所以一般设置完quit()函数,都要再加一句wait()函数;

而且对于没有循环的线程来说该函数没有任何用nothing to do;

第二种方法下,我们继承而来的run函数是没有开启循环的,所以使用这种方法的同学,就不要在去调用quit()和exit(0)函数,根本就无效;在这种情况下我们可以设置一个中断变量stopped 来中断线性;

class vtkReconstruct : public QThread{    Q_OBJECTpublic:    explicit vtkReconstruct();    ~vtkReconstruct();    void stop(){stopped=true;}//线程中断函数protected:void run();private: volatile bool stopped=false;//run函数终止变量}vtkReconstruct::~vtkReconstruct(){    if(isRunning())    {        stop();        wait();    }void vtkReconstruct:: run(){if(stopped)    {        stopped=false;        return;    }  执行任务1..........if(stopped)    {        stopped=false;        return;    }  执行任务2..........}




1 0