文件写线程安全C ++

时间:2016-06-11 15:13:05

标签: c++ multithreading mutex

我收到以下代码的错误 我正在实现线程安全写入文件如下:: 这仅用于学习目的,我正在添加更多文本,因为堆栈溢出要求我溢出文本。

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  

我想我现在已经修好了,谢谢

1 个答案:

答案 0 :(得分:1)

您不必在find_if函数中使用checkFile

这是你应该做的:

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