c++ - Boost 文件系统与 c++11 线程不兼容

标签 c++ multithreading c++11 boost boost-filesystem

我遇到了一个令人抓狂的问题,需要一些帮助。我正在尝试编写一个文件查找器或解析器来查找目录中给定格式的所有文件。我希望这是一个类,我还希望它在与 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,或者我只是用软管?

最佳答案

您需要链接到系统上的 posix 线程库

对于 gcc 或 clang,通常这是通过在命令行上提供 g++ -pthread 来完成的。

从技术上讲,您也应该指定链接到相应的动态库

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

关于c++ - Boost 文件系统与 c++11 线程不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134169/

相关文章:

c++ - 帮助 C++ 中的 ifstream 函数

c++ - 如何确定媒体文件的持续时间?

c# - 最推荐的游戏 AI 线程模式是什么以及如何实现?

Java散列锁表

c++ - 给定一个从 0 到 n 的整数 vector ,但不是全部包含在内,我如何有效地获取未包含的整数?

c++ - 没有 std::to_u16string 或 std::to_u32string 吗?

c++ - 使用参数c++创建字符串格式化c++ 20

java - Android 中用于人脸检测(随后是眼睛、 Nose 和嘴巴检测)的 OpenCV 代码

c - openMp 运行时出现峰值

c++ - 关于从函数返回大值和 move 的困惑