0

私は、concurrent_queue を使用しようとしたときに、すべてが間違っていたのだろうかと思います。スレッドを使用してファイルを処理しようとしています。Threads は、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 に答える