C++鎖定文件流fstream

目的前提

對接自動化交易,多線程下寫文件單,用ofstream追加寫的時候,會出現寫漏的情況,懷疑是多線程下,兩個線程的文件光標位置一樣了,導致有一個被覆蓋了。
因爲根據賬號不同寫不同的路徑下的文件,所以想到根據賬號不同加相應的鎖。

實現

沒有用文件鎖。因爲是ofstream,所以直接用了boost中的遞歸鎖。
大概代碼如下:

#include <boost/thread.hpp>
#include <map>
map<string, boost::recursive_mutex> s_fileorder_lock_map;
void writeFileOrder(const string &account, const string &orderstr)
{
    try {
        string filename = "order_signal.csv";
        string fullpath = qmtfilepath + "/" + account + "/" + filename;
        //根據賬號設定互斥量 加鎖
        boost::recursive_mutex::scoped_lock lock(s_fileorder_lock_map[account]);
        //LogTrace("s_lock_map,account:" << account <<", mutex:"<< &s_fileorder_lock_map[account]);

        std::ofstream ofs(fullpath, std::ios_base::app);
        ofs << orderstr;
        ofs.close();
    } catch (const exception &e) {
        //LogError("exception occurred:" << e.what());
    }
}

因爲recursive_mutex不支持賦值等操作。 用一個map保存根據賬號不同下的recursive_mutex互斥量正好,初次根據下標訪問map獲取value獲取不到時,正好它給建立一個recursive_mutex。

結論

用在項目中,簡單驗證過, 目前是可用的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章