一个疑惑的问题:QObject::killTimer: Timers cannot be stopped from another thread

本文讨论了在使用QObject的connect函数时,DirectConnection和QueuedConnection的区别,特别是在多线程环境中。在特定情况下,尝试在非创建定时器的线程中停止定时器导致了"QObject::killTimer: Timers cannot be stopped from another thread"的警告。分析了两种连接方式下槽函数的执行线程,揭示了线程同步和通信的复杂性。

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

QObject的connect函数有几种连接方式,

    a) DirectConnection,信号发送后槽函数立即执行,由sender的所在线程执行;

    b) QueuedConnection,信号发送后返回,相关槽函数由receiver所在的线程在返回到事件循环后执行;

    c) 默认使用的是Qt::AutoConnection,当sender和receiver在同一个线程内时,采用DirectConnection的方式,当sender和receiver在不同的线程时,采用QueuedConnection的方式。

 

MySerialPort::MySerialPort()

    :m_pThread(newQThread()),

      m_pCom(newQSerialPort())

{

    m_pCom->moveToThread(m_pThread);

    this->moveToThread(m_pThread);

    m_pThread->start();

 

    connect(m_pCom,&QSerialPort::readyRead,this,&MySerialPort::slotDataReady);

connect(this,&MySerialPort::sigSetCOM,this,&MySerialPort::slotSetCOM);

 

//下面的slot在sender(即resendCheckTimer)所在线程执行

    connect(&resendCheckTimer,SIGNAL(timeout()),this,SLOT(slotResendProcess()),Qt::DirectConnection);

}

 

voidMySerialPort::slotResendProcess()

{

    resendCheckTimer.stop();

}

1.  第一种情况即上述方式

 

打印信息:

main thread------------------------- QThread(0x11918c0)

MySerialPort::slotDataReady()------------------: 0x3084

MySerialPort::slotResendProcess----------------:0x2f20

2.第二种情况

改为:

connect(&resendCheckTimer,SIGNAL(timeout()),this,SLOT(slotResendProcess()));//slot 默认会在receiver(即this)所在线程执行

 

打印信息:

main thread------------------------- QThread(0x126918c0)

MySerialPort::slotDataReady()------------------: 0x2db8 //this 所在线程

MySerialPort::slotResendProcess----------------:0x2db8 //this所在线程

QObject::killTimer: Timers cannot be stopped from another thread 

注意:最下面一条警告,执行resendCheckTimer.stop()报错了,说明在第一种情况下(Qt::DirectConnection),槽函数会在receiver(即this)所在线程跟sender(即resendCheckTimer)所在线程不一致,且sender所在线程和主线程、次线程都不是一个线程,有点不明白了。。。。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值