理解QThread
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不一样
void ProgresssThreadInherit::run()
{
if (m_label == NULL) {
m_label = new QLabel;
}
qDebug() << "label memory thread id:" << Q_FUNC_INFO << this->m_label->thread()->currentThreadId();
qDebug() << "current thread id:" << Q_FUNC_INFO << QThread::currentThreadId();
while (m_stop) {
msleep(20);
}
qDebug() << Q_FUNC_INFO << "stoped";
}
void ProgresssThreadInherit::stop(bool stop)
{
qDebug() << "current thread id:" << Q_FUNC_INFO << QThread::currentThreadId();
m_stop = stop;
if (m_label) {
qDebug() << "current label memory thread id:" << Q_FUNC_INFO << m_label->thread()->currentThreadId();
}
}
结果:
在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
未完,待续