Qt-定时器不能被其它线程start

一、错误用法

TestThread::TestThread(QObject *parent)
    : QThread(parent)
{
    m_pTimer = new QTimer(this);
    connect(m_pTimer, &QTimer::timeout, this, &TestThread::timeoutSlot);
}
 
void TestThread::run()
{
    m_pTimer->start(1000);
}
 
void TestThread::timeoutSlot()
{
    qDebug() << QString::fromLocal8Bit("当前线程id:") << QThread::currentThread();
}
m_pThread = new TestThread(this);
m_pThread->start();

1.报错:

QObject: Cannot create children for a parent that is in a different thread.

(Parent is TestThread(0x709d88), parent's thread is QThread(0x6e8be8), current thread is TestThread(0x709d88) 
QObject::killTimer: Timers cannot be stopped from another thread

2.分析:

定时器不能被其它线程start。

刚开始只有主线程一个,TestThread的实例是在主线程中创建的,定时器在TestThread的构造函数中,所以也是在主线程中创建的。

当调用TestThread的start()方法时,这时有两个线程。定时器的start()方法是在另一个线程中,也就是TestThread中调用的。创建和调用并不是在同一线程中,所以出现了错误。

根据以上的原理,Qt使用计时器的线程关系(thread affinity)来决定由哪个线程发出timeout()信号。正因如此,你必须在它所处的线程中start或stop该定时器,在其它线程中启动定时器是不可能的。

二、正确用法

(一)、正确方法一

void TestThread::run()
{
    m_pTimer = new QTimer();
    m_pTimer->setInterval(1000);
    connect(m_pTimer, &QTimer::timeout, this, &TestThread::timeoutSlot);
    m_pTimer->start();
    this->exec();
}

1.注意事项

        (1)、不能像下面这样给定时器指定父对象

m_pTimer = new QTimer(this);

否则会出现以下警告:

因为TestThread对象是在主线程中创建的,它的QObject子对象也必须在主线程中创建。所以不能指定父对象为TestThread。

QObject: Cannot create children for a parent that is in a different thread.

(Parent is TestThread(0x709d88), parent's thread is QThread(0x6e8be8), current thread is TestThread(0x709d88) 

        (2)、必须要加上事件循环exec()

否则线程会立即结束,并发出finished()信号。

另外还有一点需要注意,与start一样,定时器的stop也必须在TestThread线程中,否则会出错。

(二)、正确方法二

TestClass::TestClass(QWidget *parent)
    : QWidget(parent)
{
    m_pThread = new QThread(this);
    m_pTimer = new QTimer();
    m_pTimer->moveToThread(m_pThread);
    m_pTimer->setInterval(1000);
    connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
    connect(m_pTimer, &QTimer::timeout, this, &ThreadTest::timeOutSlot, Qt::DirectConnection);
}

无需子类化线程类,通过信号启动定时器。通过moveToThread()方法改变定时器所处的线程,不要给定时器设置父类,否则该函数将不会生效。

        Qt::AutoConnection:默认值。如果接收者处于发出信号的线程中,则使用        

        Qt::DirectConnection,否则使用Qt::QueuedConnection,连接类型由发出的信号决定。

        Qt::DirectConnection:信号发出后立即调用槽函数,槽函数在发出信号的线程中执行。

        Qt::QueuedConnection:当控制权返还给接收者信号的事件循环中时,开始调用槽函数。槽函数在接收者的线程中执行。

参考文章: 

Qt——线程与定时器 - 去冰三分糖 - 博客园

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值