您提到的代码中,可能会因为重复执行 Camera::scanCamera_2D 方法导致多次启动同一个 DataProcessThread 实例而引发崩溃。为了避免这个问题,可以考虑在启动线程之前进行一些检查,确保不会重复启动相同的线程或创建新的线程实例。
以下是优化建议:
确保只创建一次
DataProcessThread:在每次调用时,检查是否已经存在对应的线程,如果已存在则跳过创建和启动。使用智能指针管理内存:这样可以避免手动删除动态分配的对象造成的内存泄漏或双重删除等问题。
添加锁机制:如果该函数可能被多个线程并发调用,考虑使用锁来保护对共享数据结构(如
m_dataProcessThreadMap和m_threadPool)的访问。
下面是改进后的示例代码:
void Camera::scanCamera_2D(QMap<QString, int> &mapCam_Name_Index)
{
    qDebug() << __LINE__ << " 123";
    // 先断开信号连接
    for(auto& info : m_dataProcessThreadMap) {
        disconnect(info.pDataProcessThread, &DataProcessThread::sigSaveNum,
                   this, &Camera::sig_SaveNum);
        qDebug() << __LINE__ << " 123";
        info.pDataProcessThread->stopRun();
        delete info.pDataProcessThread; // 删除动态分配的线程对象
    }
    qDebug() << __LINE__ << " 123";
    
    m_threadPool->clear();
    // 清空映射表
    m_dataProcessThreadMap.clear(); 
    qDebug() << __LINE__ << " 123";
    
    LE_STATUS status;
    LST_CAMERA_INFO *tempInfo = new LST_CAMERA_INFO();
    
    status = m_pCameraControl_2D->DetectCamera(m_pluginName2D.toStdString().c_str(), &tempInfo, &m_2DCamCnt);
    qDebug() << __LINE__ << " 123" << m_2DCamCnt;
    
    for(int index = 0; index < m_2DCamCnt; ++index){
        int iCameraIndex = tempInfo[index].iCameraIndex;
        
        if(-1 == tempInfo[index].iCameraIndex) {
            continue;
        }
        auto deviceName = QString(tempInfo[index].achCameraID);
        // 检查是否已经存在相机信息
        if (m_dataProcessThreadMap.contains(iCameraIndex)) {
            qDebug() << "相机索引已存在,不再处理:" << iCameraIndex;
            continue; // 跳过已存在的相机索引
        }
        qDebug()<<"2D DetectCamera return deviceName:"<<deviceName;
        mapCam_Name_Index.insert(deviceName, iCameraIndex);
        
        struct sSaveCamInfo tempSaveCamInfo;
        tempSaveCamInfo.pDataProcessThread = new DataProcessThread();
        
        QString strSavePath = m_strImagePath + "/" + deviceName;
        
        mkMutiDir(strSavePath);
        
        tempSaveCamInfo.strSavePath = strSavePath;
        
        connect(tempSaveCamInfo.pDataProcessThread, &DataProcessThread::sigSaveNum,
                this, &Camera::sig_SaveNum);
        m_dataProcessThreadMap.insert(iCameraIndex, tempSaveCamInfo);
        // 启动新的线程
        m_threadPool->start(tempSaveCamInfo.pDataProcessThread);
    }
    delete[] tempInfo; // 确保释放临时信息结构体所占用的内存
    qDebug() << __LINE__ << " 123";
}
改进点总结:
- 在插入新相机信息之前检查 
m_dataProcessThreadMap中是否已经存在此相机。 - 使用智能指针管理数据处理线程(根据需要,可以考虑使用 
std::shared_ptr或std::unique_ptr)。 - 清理完临时变量后立即释放申请的内存,以防止内存泄漏。
 - 调整了逻辑,使得对共享资源(如相机索引)有更好的控制。
内容由零声教学AI助手提供,问题来源于学员提问 


        
        
        
        
        
        
        
        
        
        
                
                
                
                
                
                
                