最近发现代码有问题 QThread: Destroyed while thread is still running
线程snap_thread.cpp
Snap_thread::Snap_thread(QLabel *pb) :QThread()
{
isRunning = true;
udp_fd = -1;
this->pb = pb;
}
void Snap_thread::run()
{
run_socket();
}
void Snap_thread::run_socket()
{
int len;
char sendbuf[256];
//sendto中使用的对方地址
struct sockaddr_in toAddr;
//在recvfrom中使用的对方主机地址
struct sockaddr_in fromAddr;
unsigned int fromLen;
char recvBuffer[128];
udp_fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(udp_fd < 0)
{
printf("创建套接字失败了.\r\n");
return;
}
//memset()函数
memset(&toAddr,0,sizeof(toAddr));
toAddr.sin_family=AF_INET;
//对方的地址和对方的主机port
toAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
toAddr.sin_port = htons(this->port);
sendbuf[0]=0x1;
if(flag_video_press_num == GUIONTIMEONE)
{
str = qpath;
str += "/car.jpg";
}
else if(flag_video_press_num == GUIONTIMETWO)
{
str = qpath;
str += "/goods.jpg";
}
strcpy(&sendbuf[1],path);
if((len=sendto(udp_fd,sendbuf,strlen(path)+2,0,(struct sockaddr*)&toAddr,sizeof(toAddr))) != strlen(path)+2)
{
printf("sendto() 函数使用失败了.\r\n");
}
printf("%d has sent %d bytes\n",this->port,len);
fromLen = sizeof(fromAddr);
if(recvfrom(udp_fd,recvBuffer,128,0,(struct sockaddr*)&fromAddr,&fromLen)<0)
{
printf("recvfrom()函数使用失败了.\r\n");
}
if(recvBuffer[0] == 2)
{
if(recvBuffer[1] == 1)
{
this->pb->setText("截图成功");
}
else if(recvBuffer[1] == -1)
{
this->pb->setText("文件名错误");
}
else
{
this->pb->setText("存储错误");
}
}
close(udp_fd);
udp_fd = -1;
}
Snap_thread::~Snap_thread(){}
void Snap_thread::setPort(int port)
{
this->port = port;
}
void Snap_thread::setPath(QString path)
{
this->qpath = "/mnt/ftp/";
qpath += path;
}
void Snap_thread::stop()
{
std::cout<<"this is stop!"<<std::endl;
this->isRunning = false;
if(udp_fd >= 0)
{
close(udp_fd);
}
this->quit();
}
在主线程调用代码如下
snap = new Snap_thread(ui->label_toast);
snap->setPort(6000);
snap->setPath(snap_save_path);
snap->start();
...
if(snap->isRunning)
{
snap->stop();
delete snap;
snap = NULL;
}
现在报 QThread: Destroyed while thread is still running
还有可能直接导致程序崩溃,我应该如何改成呢?