小弟在写一个简单服务器,想实现这样的功能:每监听到一个来自客户端的连接,就开启一个线程并获取一个子套接字进行处理。
以下是部分代码:
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
if(!tcpServer->listen(QHostAddress::LocalHost,6666))
{
//监听本地主机的6666端口,如果出错就输出错误信息,并关闭
qDebug() << tcpServer->errorString();
this->close();
}
connect(tcpServer, SIGNAL(newConnection()),
this, SLOT(getConnect()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::getConnect()//线程资源如何回收?
{
QTcpSocket *client = tcpServer->nextPendingConnection();
Thread *tid = new Thread(this);
tid->getSocket(client);
tid->start();
}
如注释所问,这样做能否达到预期(是不是每次曹函数被调用就会开启一个新的线程),线程结束后又该如何回收资源?new出来的空间有该怎么回收?由于无法知道线程什么时候结束,不知道在哪里delete
求大牛问帮忙解答,谢谢
------解决方案--------------------
线程都会结束的,除非你在里面搞了个死循环,或者可以使用线程池