多線程實現隊列數據存取的過程中,遇到一些多線程編程的基礎問題,記錄一下。
簡要類比舉例,新建了類作爲對象:
class aClass{
sturct structA{
....
};
bool processData(int a,char *b);
};
在主函數文件中有子函數需要對對象中的結構體數據進行處理:
int processClassStruct(aClass &a, aClass::structA b){
...
}
希望在主函數文件中新建兩個線程,分別執行processData和processClassStruct函數。
主函數中已聲明:
aClass a;
aClass::structA b;
int format = 0;
char *file="/home/cabin/test.xtf"
問題一:編譯時提示無法找到libpthread.so.0等
解決方法:在CMakeists.txt中完善多線程需要的配置
1、set(CMAKE_CXX_FLAGS "-std=c++14 -lpthread");
2、找到需要的庫的路徑,並在target_link_libraries完善。
問題二:調用processClassStruct時出現error:no matching function for call to ‘std::thread::_Invoker<...>
解決方法:首先,列出初始嘗試調用的方法爲
std::thread threadA(processClassStruct, a, b);
threadA.join();
編譯後出現上述描述的錯誤。
正確的調用方法如下:
std::thread threadA(processClassStruct, std::ref(a), b);
threadA.join();
問題三:調用processData時出現error:invalid use of non-static member function...
解決方法:首先,列出初始嘗試的調用方法爲
std::thread threadB(a.processData, format, file);
threadB.join();
編譯後出現上述描述的錯誤。
正確的調用方法如下:
std::thread threadB(&aClass::processData, std::ref(a), format, file);
threadB.join();