如何释放线程中创建的对象
1个回答
展开全部
1.在线程中定义一个线程释放的标识
2.在run()中用while来判断这个标识,以便于结束socket对象.
3.在thread的析构中,设定标识,并使用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;
}
}
这个线程对象的释放比较有代表性,应该可以解决很多类似的问题.
另外,方法可能还有其他的,这里只是举了一种而已.
其实,问题的关键就是:线程中创建的对象就必须在线程中释放.
PS:
经shiroki的指正,其实QT有更好的机制来释放对象.那就是deleteLater(). 于是,事情就显得非常简单,请看代码:
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();
}
2.在run()中用while来判断这个标识,以便于结束socket对象.
3.在thread的析构中,设定标识,并使用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;
}
}
这个线程对象的释放比较有代表性,应该可以解决很多类似的问题.
另外,方法可能还有其他的,这里只是举了一种而已.
其实,问题的关键就是:线程中创建的对象就必须在线程中释放.
PS:
经shiroki的指正,其实QT有更好的机制来释放对象.那就是deleteLater(). 于是,事情就显得非常简单,请看代码:
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();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询