During Symbian application development and meego application development, Q framework is a unified development framework. In many cases, a new qudpsocket must be created in qthread run to send and receive data. at this time, the release of this socket object becomes a troublesome problem.
If the socket object is directly deleted in the thread structure, the following exception occurs:
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.
Below isSolution:
◆ Define a thread release identifier in the thread
◆ Use while in run () to determine this identifier, so as to end the socket object.
◆ In the thread structure, set the ID and use quit () and wait ().
The Code is as follows:
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; } }
The release of this thread object is representative and can solve many similar problems.
In addition, there may be other methods. Here is just one.
In fact, the key to the problem is that the objects created in the thread must be released in the thread.
PS:
According to shiroki's correction, QT has a better mechanism to release objects. That is, deletelater (). Therefore, things are very simple. Please refer to the Code:
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(); }