Multi-thread fstream write data with filelock

Source: Internet
Author: User
Tags flock

# 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 ");
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 <"Thread" <m_nid + 1 <"Player data" <m_ncountmember <Endl;
Savemebbers. Open (m_strfilename.c_str (), IOS: APP );
If (! Savemebbers)
{
Savelog <"Thread" <m_nid + 1 <"Open File" <m_strfilename <"failed" <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;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.