使用单独的线程从文件预加载数据

Oli*_*erB 5 c++ multithreading c++11

我有一个小应用程序处理大量(相对较小)的文件.它按顺序运行:它从文件加载数据,对文件执行操作,然后移动到下一个文件.我注意到在运行时,CPU使用率不是100%,我想这是由于硬盘驱动器上的I/O操作所花费的时间.

因此,我们的想法是使用一个单独的线程将下一个数据与当前数据的处理并行加载到内存中(所讨论的数据只是一个int序列,存储在一个向量中).这似乎是一个非常普遍的问题,但我很难找到一个简单,简单的C++示例来做到这一点!现在C++ 0x正在进行中,使用新线程工具的简单演示代码,没有外部库,将是非常好的.

此外,虽然我知道这取决于很多事情,但是有可能对这种方法的好处(或挫折)进行有根据的猜测,例如,要加载的数据文件的大小?我想对于大文件,磁盘I/O操作很少,因为数据已经被缓冲(使用fstream(?))

奥利维尔

Luc*_*ton 4

关于如何使用某些 C++0x 线程和同步设施的玩具程序。不知道它的性能如何(我推荐马特的答案),为了举例,我的重点是清晰度和正确性。

根据您的要求,这些文件将被单独读取。然而,它们不会转换为序列int,因为我觉得这与处理而不是严格的 I/O 更相关。因此这些文件被转储到一个普通的std::string.

#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <deque>
#include <future>
#include <mutex>
#include <condition_variable>

int
main()
{
    // this is shared
    std::mutex mutex;
    std::condition_variable condition;
    bool more_to_process = true;
    std::deque<std::string> to_process;

    /* Reading the files is done asynchronously */
    std::vector<std::string> filenames = /* initialize */
    auto process = std::async(std::launch::async, [&](std::vector<std::string> filenames)
    {
        typedef std::lock_guard<std::mutex> lock_type;
        for(auto&& filename: filenames) {
            std::ifstream file(filename);
            if(file) {
                std::ostringstream stream;
                stream << file.rdbuf();
                if(stream) {
                    lock_type lock(mutex);
                    to_process.push_back(stream.str());
                    condition.notify_one();
                }
            }
        }
        lock_type lock(mutex);
        more_to_process = false;
        condition.notify_one();
    }, std::move(filenames));

    /* processing is synchronous */
    for(;;) {
        std::string file;
        {
            std::unique_lock<std::mutex> lock(mutex);
            condition.wait(lock, [&]
            { return !more_to_process || !to_process.empty(); });

            if(!more_to_process && to_process.empty())
                break;
            else if(to_process.empty())
                continue;

            file = std::move(to_process.front());
            to_process.pop_front();
        }

        // use file here
    }

    process.get();
}
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • 互斥锁、条件变量、停止标志和std::string容器在逻辑上都是相关的。您也可以用线程安全的容器/通道替换它们
  • 我使用std::async而不是std::thread因为它具有更好的异常安全特性
  • 没有错误处理可言;如果由于某种原因无法读取文件,则会默默地跳过该文件。您有多种选择:发出信号表明没有更多内容需要处理并尽快抛出来处理;或使用 aboost::variant<std::string, std::exception_ptr>将错误传递到事物的处理端(这里错误作为异常传递,但您可以使用 anerror_code或您喜欢的任何内容)。无论如何,这并不是一份详尽的清单。