最近工程上需要用到多線程調用類內成員函數,記錄一下當時出錯的問題,及解決方法。
1.首先 寫法是普通多線程調用時候的聲明,如下:
void getRegResultByOneSetpThread(const int decodeType, vector<vector<float>>& probAll, const int m_roiBegin, const int m_roiEnd,const int topN, const cv::Mat& g_oriPicMat, string& regJson)
std::thread t0(getRegResultByOneSetpThread, 0, probAll, m_roiBegin, m_roiEnd, topN, g_oriPicMat,regAll);
結果會報如下錯誤:
error: invalid use of non-static member function
2.然后查找資料,得知類內成員函數多線程調用時需要聲明為static形式,或者傳入this指針才行,(普通成員函數在參數傳遞時編譯器會隱藏地傳遞一個this指針.通過this指針來確定調用類產生的哪個對象)
Agent_Classifier 為類名。
修改為如下形式:
std::thread t0(&Agent_Classifier::getRegResultByOneSetpThread,this, 0, probAll, m_roiBegin, m_roiEnd, topN, g_oriPicMat,regAll);
結果會報如下錯誤:
error: no type named ‘type’ in ‘class std::result_of
3.原因是 線程函數 getRegResultByOneSetpThread 參數類型有引用類型,必須傳入引用類型才可以:
std::thread t0(&Agent_Classifier::getRegResultByOneSetpThread,this, 0, std::ref(probAll), m_roiBegin, m_roiEnd, topN, std::ref(g_oriPicMat), std::ref(regAll));
至此編譯通過。
參考:
https://stackoverflow.com/questions/41476077/thread-error-invalid-use-of-non-static-member-function