QT两种线程方法

2021/7/21 23:05:55

本文主要是介绍QT两种线程方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.重写QThread 的run()函数

class MyThread : public QThread

{

  protected:

    void run();

}

void MyThread::run()

{

  m_isCanRun = true;//标记可以运行

  //希望线程处理的事情

  QMutexLocker locker(&m_lock);// 此处加锁,防止访问冲突

  if(!m_isCanRun)//在每次循环判断是否可以运行,如果不行就退出循环

   {

   return;

  }

}

 

 

main

{

      MyThread thread;

      thread.start();

  //子线程指针,尽量不要去delete ,这样不安全。一般会绑定QObject::deleteLater()方法。

  connect(thread,&QThread::finished ,thread,&QObject::deleteLater);

}

 

2.QObject::movetoThread()函数

class Worker:public QObjiec

{

  Q_OBJECT

public slots:

  void dowork()

  {

  //do work

  emit dealResault(resault);

  }

signals:

  void dealResault(const QString &resault);

}

 

class Controllre: public QObject

{

  Q_OBJECT

public:

  QThread workThread();

  Controllre()

  {

  WorkerObj *worker = new WorkerObj;

  worker->movetoThread(&workThread);

  connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater); //这个信号槽必须连接,否则会内存泄漏

  connect(&workerThread,SIGNALS(started()),worker,SLOT(doWork()));

  workThread.start();

  connect(worker,SIGNAL(dealResault(QString)),this,SLOT(resault(QString)));

  }

  ~controllre()

  {

  workThread.quit();

  workerThread.wait();

  }

public slots:

  void resault(QString &data);

}



这篇关于QT两种线程方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程