Qt库中的mapreduce是否保留输入文件的顺序?

Does mapreduce from the Qt library preserve the sequence of the input files?

本文关键字:文件 输入 顺序 保留 是否 mapreduce Qt      更新时间:2023-10-16
    WordCount countWords(const QString &file)
    {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        WordCount wordCount;
        while (textStream.atEnd() == false)
            foreach (QString word, textStream.readLine().split(" "))
                wordCount[word] += 1;
        return wordCount;
    }
...
QStringList files = findFiles("../../", QStringList() << "*.cpp" << "*.h");
...
int mapReduceTime = 0;
{
    QTime time;
    time.start();
    WordCount total = mappedReduced(files, countWords, reduce);
    mapReduceTime = time.elapsed();
    qDebug() << "MapReduce" << mapReduceTime;
}

假设我想跟踪我正在处理的文件,我可以在countWord函数中创建一个全局静态变量,并在每次开始运行时增加它,以知道我正在对文件1进行一些处理吗?还是不可能知道哪个文件将首先被处理?我问是因为mapreduce允许并行处理,但我不知道操作系统将如何调度线程。

不可能确切地知道处理将以什么顺序运行,因为每个映射操作通常会花费不同的时间。

一个简单的解决方案是不处理原始文件列表,而是处理(index, filename)对的列表。

您还应该跳过空字符串,并且至少处理无法打开给定文件进行读取的错误。boolExpr == false的习惯写法为! boolExpr

typedef QPair<int, QString> FileEntry;
WordCount countWords(const FileEntry &entry)
{
    WordCount wordCount;
    QFile f(entry.second);
    if (!f.open(QIODevice::ReadOnly)) return wordCount;
    QTextStream ts(&f);
    while (!ts())
      foreach (QString word, ts().split(" ", QString::SkipEmptyParts))
        wordCount[word] ++;
    return wordCount;
}
QStringList f = findFiles("../../", QStringList() << "*.cpp" << "*.h");
QList<FileEntry> fileEntries;
fileEntries.reserve(f.size());
int i = 0;
foreach (QString file, f)
  fileEntries << qMakePair(i++, file); 
mappedReduced(fileEntries, countWords, reduce);