2014-10-01 31 views
1

我有一个令人生气的问题,我需要一些帮助。我试图编写一个文件查找程序或解析器来查找目录中给定格式的所有文件。我希望这是一个类,我也希望它在它自己的独立线程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,或者我只是被调整了?

+0

我不认为它会解决任何问题,但如果您使用C++ 11,则可以删除pthread。你使用什么gcc版本? – UldisK 2014-10-01 04:46:01

+0

至少某些版本的Ubuntu有单独的多线程版本的boost库。尝试安装所有可用的boost包并查找'* -mt.so'库。 – 2014-10-01 05:06:40

+0

我在Ubuntu上使用gcc 4.8.2。同样,没有任何* -mt库,但我认为boost库通常是多线程的,即使在我的Mac上它们都带有-mt附加语。我能够放下pthread,突然间一切正常。 – NuclearAlchemist 2014-10-01 16:26:05

回答

1

您需要链接到POSIX线程库系统

用gcc或铛上,通常这是通过在命令行上提供g++ -pthread完成。

技术上应指定与相应的动态库链接太

g++ -pthread test.cpp -lboost_system -lboost_thread -lboost_filesystem 
+0

事实证明,如果我只是从我的代码中省略-pthread选项,它就可以工作。出于某种原因,在boost :: filesystem库中使用boost线程和C++ 11线程之间存在冲突。我得到它在我的Mac上正确编译。现在,只要我能够实际识别一个目前不存在的目录,但编译至少是一个开始。 – NuclearAlchemist 2014-10-01 16:27:29

+0

@DavidSchwartz修复 – sehe 2014-10-01 23:15:17

0

使用G ++ 4.8,似乎一个人不能同时拥有编译器选项-pthread和-std = C++ 11米的标志。它们在Mac(用自制软件gcc48)和我的Ubuntu发行版(14.04LTS用g ++ - 4.8)互相排斥。只需使用-std = C++ 11。