理解QThread

  1. QThread与通常所熟知的线程(thread)有很大出入,在面向过程的语言中,我们建立一个线程的同时会传入一个函数名,这个函数名代表该线程要执行的具体代码(如图 1 所示)。<br />![](https://cdn.nlark.com/yuque/0/2018/png/215269/1544696979769-e5f8724d-0362-4dc7-8bb8-715f0a43e31e.png#width=189)<br />但是QThread里并没有线程的具体代码,QThread只是一个接口而已,目的是为操作系统提供一个用于线程调度的“句柄”。这个“句柄”即是QThread的入口(如图 2 所示)。<br />![](https://cdn.nlark.com/yuque/0/2018/png/215269/1544697130615-edfbb489-efbe-4d31-b26e-a0d43f8b61d6.png#width=492)

Qthread:

以继承的方式实现线程,同一个成员变量指针,在线程的run方法中new的内存,访问的线程id与在普通函数中访问到的线程id不一样

  1. void ProgresssThreadInherit::run()
  2. {
  3. if (m_label == NULL) {
  4. m_label = new QLabel;
  5. }
  6. qDebug() << "label memory thread id:" << Q_FUNC_INFO << this->m_label->thread()->currentThreadId();
  7. qDebug() << "current thread id:" << Q_FUNC_INFO << QThread::currentThreadId();
  8. while (m_stop) {
  9. msleep(20);
  10. }
  11. qDebug() << Q_FUNC_INFO << "stoped";
  12. }
  13. void ProgresssThreadInherit::stop(bool stop)
  14. {
  15. qDebug() << "current thread id:" << Q_FUNC_INFO << QThread::currentThreadId();
  16. m_stop = stop;
  17. if (m_label) {
  18. qDebug() << "current label memory thread id:" << Q_FUNC_INFO << m_label->thread()->currentThreadId();
  19. }
  20. }

结果:
QThread - 图1

在QThread中,默认的信号槽连接方式,是Qt::QueuedConnection
对于使用这种继承的方式实现线程是不建议的,QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread

未完,待续