每次收到数据,就创建新线程,结果 客户端 断开连接,线程依然在。
若是 加上 //subThreadContainer->quit(); //subThreadContainer->exit(); 监听程序直接没了,进程直接消失(WIN10)。
如何正确地销毁 临时创建的线程呢?
//---------------------------------------------------------------------------------------------------
void psw_edit_v2_server::socket_Read_Data_slot()
{
//收到数据
//发送线程信号emit openThreadSignal(); 创建新线程处理;
emit openThreadSignal(socket001, cipherStr);//触发openThreadSlot()创建绑定线程,将数据处理任务交给线程完成;
}
void psw_edit_v2_server::openThreadSlot(QTcpSocket *dstClientTcpSocket, QString msgText)
{
/*开启绑定一条多线程*/
qDebug() << tr("开启子线程");
subThreadContainer = new QThread(this); //创建子线程(容器);
myObjectThread = new MyWorkThreadQtEh(); //需要在线程中运行的类对象,注意不能指定父对象
myObjectThread->moveToThread(subThreadContainer); //将创建的对象移到线程容器中
//connect(subThreadContainer, SIGNAL(execThreadFun()), myObjectThread, SLOT(execThreadSlot()));//启动线程中槽函数执行耗时任务;
connect(this, &psw_edit_v2_server::execThreadFun, myObjectThread, &MyWorkThreadQtEh::execThreadSlot);
connect(subThreadContainer, SIGNAL(finished()), myObjectThread, SLOT(deleteLater())); //终止线程时要调用deleteLater槽函数
connect(subThreadContainer, SIGNAL(finished()), subThreadContainer, SLOT(deleteLater()));
connect(subThreadContainer, SIGNAL(finished()), this, SLOT(deleteLater())); //可选操作,官方就没写这条;
subThreadContainer ->start();
qDebug() << "Main QThread::currentThreadId()==" << QThread::currentThreadId();
//线程创建完成后,接着调用线程执行耗时任务;发送execThreadFun()启动子线程的信号;
emit execThreadFun(dstClientTcpSocket, msgText);
}