threadobject已经析构,thread.isrunning 是false,thread.isfinishing() 也是true,说明thread退出了,但是qtcreator调试窗口中还是可见Qthread状态竟然是正在运行,什么鬼, 特此记录下这个现象。待解。
记录:sockect只能在同一个线程对象中使用.在同一个线程创建的变量也只能在当前线程使用。在实际运用中,切记不可跨线程去使用其他线程里面的变量等。若业务需求必须要使用其他线程的数据,可通过信号槽 将该数据emit出去,由其他线程接收再进行使用。
//重写QTcpServer中的incomingConnection函数,当监听到有连接时,会调用此函数
void MyServer::incomingConnection(qintptr socketDescriptor)
{
qDebug() << "主线程id:" << QThread::currentThread();
Thread1 *thread = NULL;
QMap<int, Thread1*>::iterator iter = m_mapThread.find(socketDescriptor);
if(iter != m_mapThread.end())
thread = iter.value();
else
{
thread = new Thread1(socketDescriptor);
m_mapThread[socketDescriptor] = thread;
}
//connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));//删除thread对象
thread->start();
}
thread1.cpp
Thread1::Thread1(int socketDescriptor,QObject *parent) :
QThread(parent)
{
m_socketDescriptor = socketDescriptor;
}
Thread1::~Thread1()
{
qDebug() << "调用线程1析构函数" << QThread::currentThread();
if(m_socket != NULL)
{
delete m_socket;
m_socket = NULL;
}
}
void Thread1::run()
{
qDebug() << "启动Thread1 run()函数" << QThread::currentThread();
m_socket = new QTcpSocket();
if(m_socket->setSocketDescriptor(m_socketDescriptor))
{
qDebug()<<"setSocketDescriptor success!";
}
else
{
qDebug()<<"setSocketDescriptor error!";
}
//创建线程2,处理socket槽函数
Thread2 *thread2 = new Thread2(m_socket);
thread2->start();
QEventLoop loop;
connect(thread2, SIGNAL(finished()),&loop, SLOT(quit()));//阻塞thread1,直到thread2退出run()
loop.exec();
//删除thread2
if(thread2 != NULL)
{
delete thread2;
thread2 = NULL;
}
qDebug() << "退出Thread1 run()函数" << QThread::currentThread();
}
thread2.cpp
Thread2::Thread2(QTcpSocket *socket,QObject *parent) :
QThread(parent)
{
m_socket = socket;
}
Thread2::~Thread2()
{
qDebug() << "调用Thread2析构函数" << QThread::currentThread();
}
void Thread2::run()
{
qDebug() << "启动Thread2 run()函数" << QThread::currentThread();
connect(m_socket,SIGNAL(readyRead()),this,SLOT(readData()));
QEventLoop loop;
QObject::connect(m_socket, SIGNAL(disconnected()), &loop, SLOT(quit()));//socket断开退出thread2 run()函数
loop.exec();
qDebug() << "退出Thread2 run()函数" << QThread::currentThread();
}
void Thread2::readData()
{
qDebug() << "[" << QThread::currentThread() << "]" << "读取客户端数据:" << m_socket->readAll();
}
test.cpp
void Dialog::on_pushButton_clicked()
{
int isz = m_server->m_mapThread.size();
QMap<int, Thread1*>::iterator iter = m_server->m_mapThread.begin();
while (iter != m_server->m_mapThread.end())
{
int h = iter.key();
Thread1* th = iter.value();
if(th->isFinished())
qDebug()<<"h:"<<h<<"thread is finished";
if(th->isRunning())
qDebug()<<"h:"<<h<<"thread is isRunning";
iter++;
}
}