线程结构
以linux平台为例
线程创建
- 构造函数
public:
explicit QThread(QObject *parent = nullptr);
protected:
QThread(QThreadPrivate &dd, QObject *parent = nullptr);
线程优先级
枚举值有
- IdlePriority
- LowestPriority
- LowPriority
- NormalPriority
- HighPriority
- HighestPriority
- TimeCriticalPriority
- InheritPriority
enum Priority {
IdlePriority,
LowestPriority,
LowPriority,
NormalPriority,
HighPriority,
HighestPriority,
TimeCriticalPriority,
InheritPriority
};
class QThreadPrivate
{
QThread::Priority priority;
}
设置优先级
void setPriority(Priority priority);
获取优先级
Priority priority() const;
线程运行状态
bool isFinished() const;
bool isRunning() const;
class QThreadPrivate
{
bool running;
bool finished;
bool isInFinish; //when in QThreadPrivate::finish
}
线程栈
void setStackSize(uint stackSize);
uint stackSize() const;
class QThreadPrivate
{
uint stackSize;
}
线程的事件分发器
QAbstractEventDispatcher *eventDispatcher() const;
void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher);
线程的控制
public Q_SLOTS:
void start(Priority = InheritPriority); //线程开启
void terminate();//结束线程
void quit();//结束线程的QEventLoop
线程的等待
bool wait(unsigned long time = ULONG_MAX);
QThread调用start具体做了哪些工作
以linux平台为例,其时序为
其创建的是脱离线程的,即属性为PTHREAD_CREATE_DETACHED
- 创建线程执行QThreadPrivate的start方法
- 触发线程的started信号
emit thr->started(QThread::QPrivateSignal());
- 执行线程的默认run方法
thr->run()
- 执行exec方法
- 执行事件循环,调用QEventLoop的exec
- 执行exec方法
- 触发线程的started信号
int QThread::exec()
{
Q_D(QThread);
QMutexLocker locker(&d->mutex);
d->data->quitNow = false;
if (d->exited) {
d->exited = false;
return d->returnCode;
}
locker.unlock();
QEventLoop eventLoop;
int returnCode = eventLoop.exec();
locker.relock();
d->exited = false;
d->returnCode = -1;
return returnCode;
}