2014-12-15 4 views
0

"while"루프를 PPL 방식으로 병렬화해야합니다. 나는 Visual C++에서 MS VS 2013에서 다음 코드를 가지고있다.PPL을 사용하여 "while"루프를 병렬화하는 방법

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 방식으로 어떻게 병렬화 될 수 있습니까? 도와주세요.

+1

while 루프를 병렬 처리하기 전에 많은 시간을 들여 하드웨어가 어떻게 단일 파일에서 병렬 읽기를 지원하는지 자문 해보십시오. –

+0

텍스트 파일을 병렬로 읽어야합니다. 도움! – user3769902

답변

0

그의 의견에 사용자 High Performance Mark 힌트가 있으므로 동일한 ifstream 인스턴스에서 병렬 읽기가 정의되지 않았고 잘못된 동작을 일으킬 수 있습니다. (좀 더 자세한 논의는 질문 "Is std::ifstream thread-safe & lock-free?"을 참조하십시오.) 기본적으로이 특정 알고리즘에서는 병렬화 한계에 도달했습니다.

여러 개의 다른 파일 스트림을 병렬로 읽는 경우에도 동일한 물리 볼륨에서 모두 읽는 경우 실제로 속도가 향상되지 않습니다. 디스크 하드웨어는 실제로는 너무 많은 병렬 요청을 지원할 수 있습니다 (일반적으로 한 번에 하나씩 만, 사용 중일 때 들어오는 요청을 대기열에 넣음). 더 많은 배경 지식을 얻으려면 Mark Friedman의 Top Six FAQs on Windows 2000 Disk Performance을 확인해보십시오. 성능 카운터는 Windows에 따라 다르지만 대부분의 정보는 일반적으로 사용됩니다.