【问题标题】:concurrent_queue gives same value on each thread for try_pop()concurrent_queue 在每个线程上为 try_pop() 提供相同的值
【发布时间】:2015-08-19 05:51:30
【问题描述】:

我想知道我在尝试使用 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

我做错了什么?

【问题讨论】:

    标签: windows multithreading visual-studio-2013 concurrent-queue


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多