0

我想知道当我尝试使用 concurrent_queue 时是否完全搞错了。我正在尝试使用线程处理文件。线程从 concurrent_queue 中提取文件名并继续。我的问题是每个线程似乎处理同一个文件 4 次,因为我有 4 个线程。

我的主要目标是从队列中挑选 4 个不同的文件并独立处理它们,直到队列耗尽。

#include <string>
#include <strstream>
#include <ppl.h>
#include <concurrent_queue.h>
#include <thread>
using namespace std;
using namespace concurrency;

void ProcessQ(concurrent_queue<string> &fileQ,string folder)
{
    TxtFileReader reader;
    while (!fileQ.empty())
    {
        string fileName;
        if (fileQ.try_pop(fileName))
        {
            vector<float> fpTemplate(0);
            int n = reader.ReadTxtFile(folder+fileName, fpTemplate);
            if (n > 0)
            {
                cout << "Processed file:" << fileName<<endl;
            }
            else
                cout << "Skipping file:" << fileName<<endl;
        }

    }
}
int main()
{

    stringstream fileNameStream;
    concurrent_queue<string> fileQ;
    for (int first = 1; last<= 100; first++)
    {
            fileNameStream << first << ".txt";      
            fileQ.push(fileNameStream.str());                       
            fileNameStream.str(string());
    }

    string folder = string("E:\\Tests\\Outputs\\txts\\");

    // Create threads and exectue
    const short nThreads = 4;
    thread fileProcessorThreads[nThreads];

    for (short i = 0; i<nThreads; i++) 
    {
        fileProcessorThreads[i] = thread(ProcessQ,fileQ,folder);
    }
    for (auto& th : fileProcessorThreads) {
        th.join();
    }


    return 0;
}

}

控制台上的输出是

已处理 1.txt 已处理 1.txt 已处理 1.txt 已处理 1.txt 已处理 2.txt 已处理 2.txt 已处理 2.txt 已处理 2.txt

我究竟做错了什么?

4

1 回答 1

1

明白了,我必须使用 std::ref() 才能对队列进行共享引用。

fileProcessorThreads[i] = thread(ProcessQ,std::ref(fileQ),folder);

原始代码可能是将队列的副本发送到线程函数。

于 2015-08-19T06:18:48.927 回答