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;

  • 相关阅读:
    [Cerc2013]Magical GCD
    UVA 1393 Highways
    UVA 10214 Trees in a Wood
    [SDOI2010]大陆争霸
    Oracle逻辑读详解
    DBA_2PC_PENDING (转)
    oracle autotrace使用
    升级oracle 9i到10g
    VMware 虚拟机中添加新硬盘的方法(转载)
    ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql (转)
  • 原文地址:https://www.cnblogs.com/byfei/p/3112332.html
Copyright © 2011-2022 走看看