Qt開(kāi)發(fā):釋放線程中創(chuàng)建的QUdpSocket對(duì)象
51CTO編者按:在做Symbian應(yīng)用開(kāi)發(fā)和MeeGo應(yīng)用開(kāi)發(fā)時(shí)Q框架是一個(gè)統(tǒng)一的開(kāi)發(fā)框架,很多時(shí)候需要在QThread的run中new一個(gè)QUdpSocket來(lái)收發(fā)數(shù)據(jù).這時(shí),這個(gè)socket對(duì)象的釋放就成了一個(gè)麻煩的問(wèn)題.
如果在thread的析構(gòu)中直接delete這個(gè)socket對(duì)象,則會(huì)出現(xiàn)如下異常:
- QSocketNotifier: socket notifiers cannot be disabled from another thread
- ASSERT failure in QCoreApplication::sendEvent: “Cannot send events to objects owned by a different thread. Current thread 560cb8. Receiver ” (of type ‘QNativeSocketEngine’) was created in thread a617748″, file kernel\qcoreapplication.cpp, line 349
- Invalid parameter passed to C runtime function.
- Invalid parameter passed to C runtime function.
以下是解決方案:
◆在線程中定義一個(gè)線程釋放的標(biāo)識(shí)
◆在run()中用while來(lái)判斷這個(gè)標(biāo)識(shí),以便于結(jié)束socket對(duì)象.
◆在thread的析構(gòu)中,設(shè)定標(biāo)識(shí),并使用quit()和wait().
代碼如下:
- UdpSocketThread::UdpSocketThread(QObject *parent) :
- QThread(parent)
- {
- this->socket = 0;
- this->needStop = false;
- }
- UdpSocketThread::~UdpSocketThread()
- {
- this->needStop = true;
- quit();
- wait();
- }
- void UdpSocketThread::run()
- {
- socket = new QUdpSocket;
- connect(socket,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));
- socket->bind(2234);
- exec();
- while(this->needStop)
- {
- if(this->socket)
- {
- delete this->socket;
- this->socket = 0;
- }
- break;
- }
- }
這個(gè)線程對(duì)象的釋放比較有代表性,應(yīng)該可以解決很多類(lèi)似的問(wèn)題.
另外,方法可能還有其他的,這里只是舉了一種而已.
其實(shí),問(wèn)題的關(guān)鍵就是:線程中創(chuàng)建的對(duì)象就必須在線程中釋放.
PS:
經(jīng)shiroki的指正,其實(shí)QT有更好的機(jī)制來(lái)釋放對(duì)象.那就是deleteLater(). 于是,事情就顯得非常簡(jiǎn)單,請(qǐng)看代碼:
- UdpSocketThread::UdpSocketThread(QObject *parent) :
- QThread(parent)
- {
- socket = 0;
- }
- UdpSocketThread::~UdpSocketThread()
- {
- this->socket->deleteLater();
- quit();
- wait();
- }
- void UdpSocketThread::run()
- {
- socket = new QUdpSocket;
- connect(socket,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));
- socket->bind(2234);
- exec();
- }
Phone Club——51CTO移動(dòng)開(kāi)發(fā)線下技術(shù)沙龍
本期主題:Android應(yīng)用開(kāi)發(fā)技術(shù)進(jìn)階
地點(diǎn):北京市海淀區(qū)中關(guān)村南大街30號(hào)東聯(lián)藝術(shù)工社
演講講師:范懷宇(網(wǎng)易)
【編輯推薦】
- QTreeWidget設(shè)計(jì)解決沒(méi)有拖動(dòng)項(xiàng)問(wèn)題
- Symbian和MeeGo將統(tǒng)一開(kāi)發(fā)環(huán)境 Qt壓力很大
- QtCreator:MeeGo開(kāi)發(fā)程序入門(mén)手冊(cè)
- 諾基亞發(fā)布Qt 4.6版本 支持多點(diǎn)觸摸和手勢(shì)輸入
- 在QT SDK下構(gòu)建MeeGo Touch開(kāi)發(fā)環(huán)境