如何使用 PPL 并行化"while"循环



我需要通过PPL并行化"while"循环。我在 MS VS 2013 的视觉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::p arallel_for() 算法提供。但是此代码还具有嵌套的"while"循环,用于执行从文件读取。我需要并行化这个嵌套的"while"循环。如何通过 PPL 并行化这个嵌套的"while"循环。请帮忙。

正如用户高性能标记在他的评论中暗示的那样,来自同一ifstream实例的并行读取将导致未定义和不正确的行为。(有关更多讨论,请参阅问题"std::ifstream 线程安全且无锁吗?"。使用这种特定算法,您基本上处于并行化极限。

作为旁注,如果它们都是从同一个物理卷读取的,即使并行读取多个不同的文件流也不会真正加快速度。磁盘硬件实际上只能支持这么多并行请求(通常一次不超过一个,在繁忙时排队传入的任何请求)。有关更多背景信息,您可能需要查看 Mark Friedman 关于 Windows 2000 磁盘性能的六大常见问题解答;性能计数器特定于 Windows,但大多数信息都是常规用途。

最新更新