1. 程式人生 > >一個疑惑的問題:QObject::killTimer: Timers cannot be stopped from another thread

一個疑惑的問題:QObject::killTimer: Timers cannot be stopped from another thread

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所線上程和主執行緒、次執行緒都不是一個執行緒,有點不明白了。。。。