【问题标题】:How to parallelize "while" loop by the using of PPL如何使用 PPL 并行化“while”循环
【发布时间】:2014-12-15 16:46:23
【问题描述】:

我需要通过 PPL 并行化“while”循环。我在 MS VS 2013 的 Visual C++ 中有以下代码。

int WordCount::CountWordsInTextFiles(basic_string<char> p_FolderPath, vector<basic_string<char>>& p_TextFilesNames)
{
    // Word counter in all files.
    atomic<unsigned> wordsInFilesTotally = 0;
    // Critical section.
    critical_section cs;

    // Set specified folder as current folder.
    ::SetCurrentDirectory(p_FolderPath.c_str());

    // Concurrent iteration through p_TextFilesNames vector.
    parallel_for(size_t(0), p_TextFilesNames.size(), [&](size_t i)
    {
        // Create a stream to read from file.
        ifstream fileStream(p_TextFilesNames[i]);
        // Check if the file is opened
        if (fileStream.is_open())
        {
            // Word counter in a particular file.
            unsigned wordsInFile = 0;

            // Read from file.
            while (fileStream.good())
            {
                string word;
                fileStream >> word;
                // Count total number of words in all files.
                wordsInFilesTotally++;
                // Count total number of words in a particular file.
                wordsInFile++;
            }

            // Verify the values.
            cs.lock();
            cout << endl << "In file " << p_TextFilesNames[i] << " there are " << wordsInFile << " words" << endl;
            cs.unlock();
        }
    });
    // Destroy critical section.
    cs.~critical_section();

    // Return total number of words in all files in the folder.
    return wordsInFilesTotally;
}

此代码在外循环中通过 std::vector 进行并行迭代。并行性由 concurrency::parallel_for() 算法提供。但是这段代码也有嵌套的“while”循环,执行从文件中读取。我需要并行化这个嵌套的“while”循环。这个嵌套的“while”循环如何通过 PPL 并行化。请帮忙。

【问题讨论】:

  • 在您花费大量时间尝试并行化 while 循环之前,请先问问自己您的硬件如何支持从单个文件并行读取。
  • 我需要并行读取文本文件。救命!

标签: visual-c++ parallel-processing ppl


【解决方案1】:

正如用户High Performance Mark 在他的评论中暗示的那样,从同一个ifstream 实例并行读取将导致未定义和不正确的行为。 (有关更多讨论,请参阅问题 "Is std::ifstream thread-safe & lock-free?"。)您基本上处于此特定算法的并行化限制。

附带说明,如果它们都是从同一个物理卷中读取的,即使并行读取多个不同的文件流也不会真正加快速度。磁盘硬件实际上只能支持这么多的并行请求(通常一次不超过一个,在忙时排队进入任何请求)。有关更多背景信息,您可能需要查看 Mark Friedman 的 Top Six FAQs on Windows 2000 Disk Performance;性能计数器是特定于 Windows 的,但大部分信息都是通用的。

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多