zoukankan      html  css  js  c++  java
  • 多线程fstream带文件锁写数据

    #include <fstream>
    #include <iostream>
    #include <stdlib.h>
    #include <vector>
    #include <string>
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <sys/file.h>
    #include <string.h>

     int m_nCountMember;
     vector <string> vectData;
     inline void PutInt(string &str,int nCount)
     {
      char szBuffer[1024] = {0};
      sprintf(szBuffer,"%d",nCount );
      str += szBuffer;
     }
     inline void PutInt(string &str,string strData)
     {
      str += strData;
     }

    bool  Print(CRole* pRole,string filename)
    {
     if (NULL == pRole)
      return false;
     string strData;
     PutInt(strData, pRole->account_name);
     PutInt(strData, "\t");
     PutInt(strData, pRole->role_name);
     PutInt(strData, "\t");
     PutInt(strData, pRole->m_nRoleCreateTime);
     PutInt(strData, "\t");
     PutInt(strData, pRole->m_nOnline);
     PutInt(strData, "\t");
     PutInt(strData, pRole->m_nLastOnlineTime);
     PutInt(strData, "\t\t");
     PutInt(strData, pRole->m_nRolePetMaxLv);
     PutInt(strData, "\t");
     PutInt(strData, 0);
     vectData.push_back(strData);
     m_nCountMember++;
     if (m_nCountMember % 20000 == 0 && 0 < m_nCountMember)
     {
      ofstream saveMebbers;
      string Logname = filename + "Log.txt";
      ofstream saveLog(Logname.c_str(), ios::app);
      saveLog << "线程" << m_nID + 1 << "玩家数据" << m_nCountMember<< endl;
      saveMebbers.open(m_strfilename.c_str(), ios::app);
      if (!saveMebbers)
      {
       saveLog << "线程" << m_nID + 1 << "打开文件" << m_strfilename << "失败" << endl;
       return false;
      }
      int nfd = open(m_strfilename.c_str(), O_WRONLY | O_CREAT);
      flock(nfd, LOCK_EX);
      for (int i = 0; i < vectData.size(); i++)
       saveMebbers << vectData[i] << endl;
      flock(nfd, LOCK_UN);
      vectData.clear();
      saveMebbers.close();
     }
     return true;

  • 相关阅读:
    VLC通过RTSP地址向IPC取流播放不了问题排查
    linux opt分区扩容操作案例
    win10远程桌面报错"出现身份验证错误"
    linux通过expect实现脚本自动交互
    oracle通过触发器记录登陆主机ip
    linux root密码忘记重置
    linux双网卡配置
    Tomcat报错合集
    UFT(QTP)中的Object Repository
    利用JAVA反射机制设计通用的DAO
  • 原文地址:https://www.cnblogs.com/byfei/p/3112332.html
Copyright © 2011-2022 走看看