我有一个令人生气的问题,我需要一些帮助。我试图编写一个文件查找程序或解析器来查找目录中给定格式的所有文件。我希望这是一个类,我也希望它在它自己的独立线程main()中运行。我使用的是Ubuntu 14.04LTS,它的升级安装(1.54)。这里是我的代码的香草版本,只是连接到boost :: system。Boost文件系统与C++ 11线程不兼容
#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,或者我只是被调整了?
我不认为它会解决任何问题,但如果您使用C++ 11,则可以删除pthread。你使用什么gcc版本? – UldisK 2014-10-01 04:46:01
至少某些版本的Ubuntu有单独的多线程版本的boost库。尝试安装所有可用的boost包并查找'* -mt.so'库。 – 2014-10-01 05:06:40
我在Ubuntu上使用gcc 4.8.2。同样,没有任何* -mt库,但我认为boost库通常是多线程的,即使在我的Mac上它们都带有-mt附加语。我能够放下pthread,突然间一切正常。 – NuclearAlchemist 2014-10-01 16:26:05