類內成員函數 多線程調用 調試記錄


 最近工程上需要用到多線程調用類內成員函數,記錄一下當時出錯的問題,及解決方法。

 

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

https://stackoverflow.com/questions/28950835/c-error-no-type-named-type-in-class-stdresult-ofvoid-stdunordered


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM