[英]Boost filesystem incompatible with c++11 threads
我遇到了一個令人困擾的問題,需要我的幫助。 我試圖編寫一個文件查找器或解析器,以查找目錄中給定格式的所有文件。 我希望這是一個類,並且我也希望它在與main()自己的單獨線程中運行。 我正在使用Ubuntu 14.04LTS及其增強安裝(1.54)。 這是我的代碼的原始版本,僅與boost :: system鏈接。
#include <iostream>
#include <thread>
#include <vector>
#include <string>
class fileFinder {
private:
std::string dName;
public:
fileFinder() : dName("") { };
fileFinder(const std::string &dirName) : dName(dirName) { };
void runFileFinder(void) {
std::string fileFinderName = "Hi from filefinder!";
std::cout << fileFinderName << std::endl;
};
};
int main(int argc, char *argv[]) {
//Get the dirname, not safe yet
std::string dirName = argv[1];
fileFinder fFinderThread(dirName);
std::thread t1(&fileFinder::runFileFinder, &fFinderThread);
t1.join();
return EXIT_SUCCESS;
}
當我編譯時,一切工作都很好,實例化了該類,然后在單獨的線程中運行。 我將鏈接到boost_system只是為了表明一切仍然正常。
> g++ -g -Wall -I/usr/include/boost/ -c rFileFinder.cpp -std=c++11 -pthread
> g++ -g -Wall rFileFinder.o -o rFileFinder -L/usr/lib/x86_64-linux-gnu/ -lboost_system -std=c++11 -pthread
> ./rFileFinder abcd
Hi from filefinder: abcd
現在,由於我要查找某種類型的所有文件,因此使用boost :: filesystem會很棒。 即使嘗試鏈接到boost :: filesystem庫也會產生運行時線程錯誤(只需將-lboost_filesystem添加到庫中)。
> g++ -g -Wall -I/usr/include/boost/ -c rFileFinder.cpp -std=c++11 -pthread
> g++ -g -Wall rFileFinder.o -o rFileFinder -L/usr/lib/x86_64-linux-gnu/ -lboost_system -lboost_filesystem -std=c++11 -pthread
> ./rFileFinder abcd
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread. Operation not permitted
Aborted (core dumped)
因此,這使我發瘋,因為我將需要同時具有多線程功能(這不僅僅是問題的這一部分)。 我試圖從互聯網上挑出這個答案,但是基本上我遇到的所有事情都是關於在編譯和鏈接器步驟中如何正確地鏈接到c ++ 11或pthread。 有沒有辦法讓我同時使用std :: thread和boost :: filesystem,還是我只管了?
您需要鏈接到系統上的posix線程庫
對於gcc或clang,通常是通過在命令行上提供g++ -pthread
來完成的。
從技術上講,您也應該指定與相應的動態庫鏈接
g++ -pthread test.cpp -lboost_system -lboost_thread -lboost_filesystem
使用g ++ 4.8,似乎不能同時為編譯器選項同時使用-pthread和-std = c ++ 11標志。 它們在Mac(使用自制Gcc48)和我的Ubuntu發行版(使用g ++-4.8的14.04LTS)上相互排斥。 只需使用-std = c ++ 11。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.