Qt源码分析--QThread(4)

这篇博客深入探讨了QThread类的关键功能,包括获取线程的循环级别(loopLevel)、设置和获取线程优先级(priority)、请求线程中断(requestInterruption)以及线程的执行(run)和事件调度。QThread::exec()会增加线程的循环级别,requestInterruption()则是建议性地请求中断线程,而run()通常调用exec()开始线程执行。此外,还介绍了设置事件分派器(setEventDispatcher)的方法,用于自定义线程的事件处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.int loopLevel() const;

int QThread::loopLevel() const
{
    Q_D(const QThread);
    return d->data->eventLoops.size();
}

返回当前线程的looplevel. QThread::exec()会增加looplevel计数。

2.Priority priority() const;

QThread::Priority QThread::priority() const
{
    Q_D(const QThread);
    QMutexLocker locker(&d->mutex);
    // mask off the high bits that are used for flags
    return Priority(d->priority & 0xffff);
}

返回线程的优先级。

3. void requestInterruption();

void QThread::requestInterruption()
{
    if (this == QCoreApplicationPrivate::theMainThread.loadAcquire()) {
        qWarning("QThread::requestInterruption has no effect on the main thread");
        return;
    }
    Q_D(QThread);
    // ### Qt 6: use std::atomic_flag, and document that
    // requestInterruption/isInterruptionRequested do not synchronize with each other
    QMutexLocker locker(&d->mutex);
    if (!d->running || d->finished || d->isInFinish)
        return;
    d->interruptionRequested.store(true, std::memory_order_relaxed);
}

请求中断线程。该请求是建议性的,由线程上运行的代码来决定它是否以及如何应此类请求采取行动。如下例子:

while(<condition>) {
  if(QThread::currentThread()->isInterruptionRequested())
    return;
  ...
}

4. virtual void run();

void QThread::run()
{
    (void) exec();
}

线程的起点。 调用 start() 后,新创建的线程调用此函数。 默认实现只是调用 exec()。

5.void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher);

void QThread::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
{
    Q_D(QThread);
    if (d->data->hasEventDispatcher()) {
        qWarning("QThread::setEventDispatcher: An event dispatcher has already been created for this thread");
    } else {
        eventDispatcher->moveToThread(this);
        if (eventDispatcher->thread() == this) // was the move successful?
            d->data->eventDispatcher = eventDispatcher;
        else
            qWarning("QThread::setEventDispatcher: Could not move event dispatcher to target thread");
    }
}

将线程的事件分派器设置为eventDispatcher。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天进步2015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值