2016-06-11 6 views
-1

아래 코드에 대한 오류가 발생했습니다. 아래와 같은 파일에 스레드 안전 쓰기를 구현합니다 :: 이것은 학습 목적으로 만 사용되며 스택 오버플로가 오버플로를 원하기 때문에 더 많은 텍스트를 추가하고 있습니다. 본문.파일 쓰기 스레드 안전 C++

class OpenFile 
{ 
    string fileName; 
    static map<string, unique_ptr<mutex>> fmap; 
    bool flag; 
public : 
    OpenFile(string file) : fileName(file) { 
     try { 
      if(checkFile(file)) 
      { 
       flag = false; 
       fmap.emplace(file, make_unique<mutex>()); 
      } 
      else 
      { 
       flag = true; 
      } 
     } 
     catch(string str) 
     { 
      cout << str << endl; 
     } 
    } 
    void writeToFile(const string& str) const 
    { 
     if (flag) 
     { 
      lock_guard<mutex> lck(*fmap.find(fileName)->second); 
      ofstream ofile(fileName, ios::app); 
      ofile << "Writing to the file " << str << endl; 
      ofile.close(); 
     } 
     else 
     { 
      ofstream ofile(fileName, ios::app); 
      ofile << "Writing to the file " << str << endl; 
      ofile.close(); 
     } 
    } 
    string ReadFile() const 
    { 
     string line; 
     if (flag) 
     { 
      lock_guard<mutex> lck(*fmap.find(fileName)->second); 
      ifstream ifile(fileName, ios::in); 
      getline(ifile, line); 
      ifile.close(); 
     } 
     else 
     { 
      ifstream ifile(fileName, ios::in); 
      getline(ifile, line); 
      ifile.close(); 
     } 
     return line; 
    } 
    OpenFile() = delete; 
    OpenFile& operator=(const OpenFile& o) = delete; 
    static bool checkFile(string& fname); 
}; 


bool OpenFile::checkFile(string& fname) 
{ 
    if (fmap.find(fname)==fmap.end()) 
    { 
     return true; 
    } 
    else 
     return false; 
} 

초기 오류가 있기 때문에 스레드 심판에 의해 데이터 .. VS2015 :: 나는 지금 그것을 해결 한 생각

Description Project Line Suppression State 
'bool OpenFile::checkFile::<lambda_2bd4a02838a970867505463f4b7b6b9e>::operator()(const std::pair<std::string,std::unique_ptr<std::mutex,std::default_delete<_Ty>>>) const': cannot convert argument 1 from 'std::pair<const _Kty,_Ty>' to 'const std::pair<std::string,std::unique_ptr<std::mutex,std::default_delete<_Ty>>>' BoQian 43 

에서 오류를 통과하지이었다 당신은 그나마 당신에게

+0

' unique_ptr'쌍에 복사 가능한되지 않으며, 기억 나? – LogicStuff

+0

if (find_if (fmap.begin(), fmap.end(), [& fname] (자동 및 m) – AnatolyS

+0

나는 학습 모드에 있는데, 나는 명시 적이지만, 짧은 시간에 너무 많이 배우기 때문에 머리를 쓰고있다. P는 지금 그것을 볼 수 있습니다. –

답변

1

감사합니다 checkFile 함수에서 find_if을 사용해야합니다.

이것은 당신이해야하는 방법입니다

bool OpenFile::checkFile(string& fname) 
{ 
    return fmap.find(fname) != fmap.end(); 
} 
+0

고맙다, 지금 일하는 것 같다 :) –