0

我需要通过 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 并行化。请帮忙。

4

1 回答 1

0

正如用户High Performance Mark在他的评论中暗示的那样,来自同一ifstream实例的并行读取将导致未定义和不正确的行为。(有关更多讨论,请参阅问题“std::ifstream 线程安全且无锁吗?”。)您基本上处于此特定算法的并行化限制。

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

于 2015-01-24T20:21:08.043 回答