【发布时间】:2014-10-01 04:33:21
【问题描述】:
我遇到了一个令人抓狂的问题,需要一些帮助。我正在尝试编写一个文件查找器或解析器来查找目录中给定格式的所有文件。我希望这是一个类,并且我还希望它在与 main() 不同的线程中运行。我正在使用 Ubuntu 14.04LTS,它是 boost 安装 (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 ,或者我只是被冲洗了?
【问题讨论】:
-
我认为它不会解决任何问题,但如果你使用 c++11,你可以放弃 pthread。你用的是什么 gcc 版本?
-
至少某些版本的 Ubuntu 具有独立的多线程版本的 boost 库。尝试安装所有可用的 boost 包并查找
*-mt.so库。 -
我在 Ubuntu 上使用 gcc 4.8.2。同样,没有任何 *-mt 库,但我认为 boost 库通常是多线程的,即使在我的 mac 上它们都带有 -mt 词缀。我能够删除 pthread,突然一切正常。
-
在我的系统(不是 Ubuntu)上有单独的 boost...-mt.so 库。您可能错过了一些增强包。如果 boost 本身不使用
-std=c++11编译,则 boost 也会在使用-std=c++11编译的程序中出现异常。
标签: c++ multithreading c++11 boost boost-filesystem