用C++编一个双人格斗小游戏大全,类似于m...

&&/&&&&/&&&&/&&
【例1.1】本教程第一个C++程序,输出一行字符: &This is a C++ program.&。程序如下:
#include &iostream&
//包含头文件iostream
//使用命名空间std
int main( )
cout&&&This is a C++ program.&;
在运行时会在屏幕上输出以下一行信息:
This is a C++ program.
用main代表&主函数&的名字。每一个C++程序都必须有一个 main 函数。main前面的int的作用是声明函数的类型为整型。程序第6行的作用是向操作系统返回一个零值。如果程序不能正常执行,则会自动向操作系统返回一个非零值,一般为-1。
函数体是由大括号{& }括起来的。本例中主函数内只有一个以cout开头的语句。注意C++所有语句最后都应当有一个分号。
再看程序的第1行&#include &iostream&&,这不是C++的语句,而是C++的一个预处理命令,它以&#&开头以与C++语句相区别,行的末尾没有分号。#include &iostream&是一个&包含命令&,它的作用是将文件iostream的内容包含到该命令所在的程序文件中,代替该命令行。文件iostream的作用是向程序提供输入或输出时所需要的一些信息。iostream是i-o-stream 3个词的组合,从它的形式就可以知道它代表&输入输出流&的意思,由于这类文件都放在程序单元的开头,所以称为&头文件&(head file)。在程序进行编译时,先对所有的预处理命令进行处理,将头文件的具体内容代替 #include命令行,然后再对该程序单元进行整体编译。
程序的第2行& & 的意思是&使用命名空间std&。C++标准库中的类和函数是在命名空间std中声明的,因此程序中如果需要用到C++标准库(此时就需要用#include命令行),就需要用& &作声明,表示要用到命名空间std中的内容。
在初学C++时,对本程序中的第1, 2行可以不必深究,只需知道:如果程序有输入或输出时,必须使用&#include &iostream&&命令以提供必要的信息,同时要用&& ,使程序能够使用这些信息,否则程序编译时将出错。
【例1.2】求a和b两个数之和。可以写出以下程序:
// 求两数之和
(本行是注释行)
#include &iostream&
//预处理命令
//使用命名空间std
int main( )
//主函数首部
//函数体开始
//定义变量
cin&&a&&b;
//输入语句
//赋值语句
cout&&&a+b=&&&sum&&
//输出语句
//如程序正常结束,向操作系统返回一个零值
//函数结束
本程序的作用是求两个整数a和b之和sum。第1行&//求两数之和&是一个注释行,C++规定在一行中如果出现&//&,则从它开始到本行末尾之间的全部内容都作为注释。
如果在运行时从键盘输入
& & 123& 456↙
& & a+b=579
【例1.3】给两个数x和y,求两数中的大者。在本例中包含两个函数。
#include &iostream& //预处理命令
int max(int x,int y) //定义max函数,函数值为整型,形式参数x,y为整型
{ //max函数体开始
//变量声明,定义本函数中用到的变量z为整型
z=x; //if语句,如果x&y,则将x的值赋给z
else z=y; //否则,将y的值赋给z
return(z); //将z的值返回,通过max带回调用处
} //max函数结束
int main( ) //主函数
{ //主函数体开始
int a,b,m; //变量声明
cin&&a&&b; //输入变量a和b的值
m=max(a,b); //调用max函数,将得到的值赋给m
cout&&&max=&&&m&&'\n'; //输出大数m的值
return 0; //如程序正常结束,向操作系统返回一个零值
} //主函数结束
本程序包括两个函数:主函数main和被调用的函数max。程序运行情况如下:
18& 25 ↙ &(输入18和25给a和b)
max=25 &(输出m的值)
注意输入的两个数据间用一个或多个空格间隔,不能以逗号或其他符号间隔。
在上面的程序中,max函数出现在main函数之前,因此在main函数中调用max函数时,编译系统能识别max是已定义的函数名。如果把两个函数的位置对换一下,即先写main函数,后写max函数,这时在编译main函数遇到max时,编译系统无法知道max代表什么含义,因而无法编译,按出错处理。
为了解决这个问题,在主函数中需要对被调用函数作声明。上面的程序可以改写如下:
#include &iostream&
int main( )
int max(int x,int y); //对max函数作声明
int a,b,c;
cin&&a&&b;
c=max(a,b); //调用max函数
cout&&&max=&&&c&&
int max(int x,int y) //定义max函数
if(x&y) z=x;
return(z);
只要在被调用函数的首部的末尾加一个分号,就成为对该函数的函数声明。函数声明的位置应当在函数调用之前。
下面举一个包含类(class)和对象(object)的C++程序,目的是使读者初步了解C++是怎样体现面向对象程序设计方法的。
【例1.4】包含类的C++程序。
#include &iostream&// 预处理命令
class Student// 声明一个类,类名为Student
private: // 以下为类中的私有部分
// 私有变量num
// 私有变量score
public: // 以下为类中的公用部分
void setdata( ) // 定义公用函数setdata
cin&& // 输入num的值
// 输入score的值
void display( ) // 定义公用函数display
cout&&&num=&&&num&& // 输出num的值
cout&&&score=&&&score&&//输出score的值
}; // 类的声明结束
Student stud1,stud2; //定义stud1和stud2为Student类的变量,称为对象
int main( )// 主函数首部
stud1.setdata( );
// 调用对象stud1的setdata函数
stud2.setdata( );
// 调用对象stud2的setdata函数
stud1.display( );
// 调用对象stud1的display函数
stud2.display( );
// 调用对象stud2的display函数
在一个类中包含两种成员:数据和函数,分别称为数据成员和成员函数。在C++中把一组数据和有权调用这些数据的函数封装在一起,组成一种称为&类(class)&的数据结构。在上面的程序中,数据成员num,score和成员函数setdata,display组成了一个名为Student的&类&类型。成员函数是用来对数据成员进行操作的。也就是说,一个类是由一批数据以及对其操作的函数组成的。
类可以体现数据的封装性和信息隐蔽。在上面的程序中,在声明Student类时,把类中的数据和函数分为两大类:private(私有的)和public(公用的)。把全部数据(num,score)指定为私有的,把全部函数(setdata,display)指定为公用的。在大多数情况下,会把所有数据指定为私有,以实现信息隐蔽。
具有&类&类型特征的变量称为&对象&(object)。
程序中第18~24行是主函数。
程序运行情况如下:
↙& &(输入学生1的学号和成绩)
↙& &(输入学生2的学号和成绩)
num=1001 &(输出学生1的学号)
score=98.5 & (输出学生1的成绩)
num=1002 &(输出学生2的学号)
score=76.5 & (输出学生2的成绩)
推荐文章 TOP10用C/C++写了几个常用函数,封装在一个类中。
一、头文件【存为:utils.h】
#ifndef _GOOME_COMM_UTILS_H_
#define _GOOME_COMM_UTILS_H_
#include &sys/time.h&
#include &string&
#include &sys/types.h&
#include &sys/stat.h&
#include &unistd.h&
#include &stdio.h&
#include &stdlib.h&
#include &string.h&
#include &vector&
#include &signal.h&
#define MYERRMSG(fmt,args...)& ; printf("[%s中, 第
%d 行 ]; "fmt"\r\n" , __FILE__, __LINE__, ##args);
void*& (* ThreadFunc) (void*);
class CUtils
void& create_pthread(int socket,&
ThreadFunc& threadFunc,& int
nThreadStackSize);
void& connNumInc();
static& void& connNumDec();
static& int&&
getConnNum();
&&static& bool
& findUidFromMap(string& strSimID,
string& strUID);
static& void&&
pushUid2Map(string& strSimID,
string& strUserID);
&&//DDMMYYHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时+8
static& void&
transferTimeStr(char* posTime, char* ownerTimeStr);
&&//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时+8
static& void&
transferTimeStr2(char* posTime, char* ownerTimeStr);
&&//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时 不变
static& void&
transferTimeStr3(char* posTime, char* ownerTimeStr);
void& initConnPool(string&
strMysqlIp,& string& strUser,
string&& strPwd,
string& strDbName,& int
nMysqlPort, int nConnNum);
&&& //根据SimID,
取一个用户的UserID 。取到后将 bGetUserId置为 true
static& int&&
getUserIdFromMysql(string& strSimID,
string& strUserID, bool&
bGetUserId)&;&
sendmsg2MQ(string&& sMsg);
void& shutdownMQ();&
static& void& initMQ(
string& strActiveMqIp,& int
nActiveMqPort);
&& static&
void& initMC(
string&& szMemcachedServer, int
getFromMc(string& strKey,&
string& strValue );
setMemcached(string& strKey,&
string& strValue );
static& void& write_file(char*
szContent);
static& void&
write_file_bin(char* pContent, int nLen);
static& void& InitDaemon();
static& void& Hex2Ascii(char*
pSrcHex, int nSrcLen,& char*
pDstAscii);
static& int&&
setPthreadAtrr(pthread_attr_t&&
thread_attr, size_t& stack_set_size);
static& int&&
split(const string& input, const
string& delimiter,
vector&string&&
results, bool includeEmpties);
static& int&&
getFileLen(FILE* fp);
static& string&
getY_M_D_H_M_S();
static& string&
getYMDHMS();
static& string& getY_M_D();
static& string& getYMD();
static& string&
getHH_MM_SS();
static& string&
getHHMMSS();
二、源代码【存为:utils.cpp】
&stdarg.h&
#include &pthread.h&
&activemq/library/ActiveMQCPP.h&
#include &decaf/lang/Thread.h&
&decaf/lang/Runnable.h&
&decaf/util/concurrent/CountDownLatch.h&
#include &decaf/lang/Integer.h&
#include &decaf/util/Date.h&
&activemq/core/ActiveMQConnectionFactory.h&
&activemq/util/Config.h&
#include &cms/Connection.h&
#include &cms/Session.h&
#include &cms/TextMessage.h&
#include &cms/BytesMessage.h&
#include &cms/MapMessage.h&
&libmemcached/memcached.h&
#include "utils.h"
#include "hex2ascii.h"
#include "mutex.h"
#include "configMqMcSql.h"
#include "encapsulation_mysql.h"
#include "connPool.h"
using namespace activemq::
using namespace decaf::util::
using namespace decaf::
using namespace decaf::
using namespace EncapM
g_fp=NULL;
FILE*&& g_fp_bin=NULL;
CMutex& g_mutexWriteF
CMutex& g_mutexWriteFile_B
sConfigMqMcSql&
g_utilConfigMqMcS
CConnPoolV2&
cms::ConnectionFactory*& g_conF
CMutex& g_mutexSimU
map&string, string&
g_nConnNum = 0;
CMutex& g_mutexConnN
void CUtils::create_pthread(int socket,
ThreadFunc& threadFunc ,& int
nThreadStackSize)
&& char tmp[100];
&&int i=0, ret=0;
&&pthread_t&
&&pthread_attr_t&&
CUtils::setPthreadAtrr(pthread_attr,&
nThreadStackSize);//设置栈尺寸
pthread_create(&pid,&
&pthread_attr, threadFunc, (void*)socket);
&&if (ret != 0)
close(socket);
CUtils::connNumDec();
sprintf(tmp,& "Create pthread error [socket: %d ],
close it, cur conn num:%d ***\r\n", socket,
CUtils::getConnNum());
printf(tmp);
CUtils::write_file(tmp
sprintf(tmp, "Create pthread succ! [socket: %d ]\r\n",
socket);&&&&
printf(tmp);
CUtils::write_file(tmp );&&
pthread_detach(pid);&&&
void CUtils::connNumInc()
guard(g_mutexConnNum);
&g_nConnNum++;
void CUtils::connNumDec()
guard(g_mutexConnNum);
&& if(g_nConnNum &
&&g_nConnNum--;
CUtils::getConnNum()
& return g_nConnN
CUtils::findUidFromMap(string& strSimID,
string& strUserID)
& strUserID="00000";
& map&string,
string&::iterator&
guard(g_mutexSimUid);&
& ite = g_sim_uid.find(strSimID);
& if(ite != g_sim_uid.end())
&&& strUserID =
&& printf("get&
[simid:%s,& userid:%s]&
from&& map
succ\n",& strSimID.c_str(),
strUserID.c_str());
CUtils::pushUid2Map(string& strSimID,
string& strUserID)
&&//写本地缓存
guard(g_mutexSimUid);&
&&g_sim_uid[strSimID]
=& strUserID;&
&&printf("[simid:%s,&
userid:%s]& push to& map
succ\n",& strSimID.c_str(),
strUserID.c_str());
//DDMMYYHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void CUtils::transferTimeStr(char* posTime, char*
ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(day, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(year
, posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
&&& int nHour =
(atoi(hour) + 8) % 24;//防止小时大于24
sprintf(hour, "%d", nHour);
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);
//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void& CUtils::transferTimeStr2(char* posTime,
char* ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(year, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(day ,
posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
&&& int nHour =
(atoi(hour) + 8) % 24;//防止小时大于24
sprintf(hour, "%d", nHour);
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);&&
//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void& CUtils::transferTimeStr3(char* posTime,
char* ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(year, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(day ,
posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);&&
void& CUtils::initConnPool(string&
strMysqlIp,& string& strUser,
string&& strPwd,
string& strDbName,& int
nMysqlPort, int nConnNum)
&& char tmp[100];
&& static int&
nCount_ConnPool = 0;
&& if(nCount_ConnPool
int nRet =
g_connPool.Init(strMysqlIp,&&&
strUser,& strPwd,&
strDbName,&&&
nMysqlPort,&& nConnNum);
if(nRet != 0)
sprintf(tmp, "init conn pool fail** \n");
printf(tmp);
CUtils::write_file(tmp);&
&&catch(...)
sprintf(tmp, "init conn pool exception** \n");
printf(tmp);
CUtils::write_file(tmp);&
&& nCount_ConnPool =
//根据SimID, 取一个用户的UserID 。取到后将 bGetUserId置为
CUtils::getUserIdFromMysql(string& strSimID,
string& strUserID, bool&
bGetUserId)
&&char szSQL[1000],
tmp[1000];
&&bGetUserId =
&&CEncapMysql*&
pEM = NULL;
&&&&sprintf(szSQL,
"select sim_id, user_id from& gpsbox.t_user
where& sim_id='%s'", strSimID.c_str());
pEM = (CEncapMysql*)g_connPool.getOneConn();//从连接池借一个连接
if(pEM == NULL)
sprintf(tmp, "get& conn&
from& conn_pool err** \r\n");
printf(tmp);
CUtils::write_file(tmp);&
&&&&&&&&&&
return -1;
//查询,并取到结果集
pEM-&SelectQuery(szSQL);
if(nRet!=0)
g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[%s]SelectQuery& err[nRet=%d]**
\r\n", szSQL, nRet);
printf(tmp);
CUtils::write_file(tmp);&
return -2;
//取一行& &
if( !pEM-&FetchRow())
& g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[mysql] [sim_id:%s& has not
userid**]\r\n",& strSimID.c_str());
printf(tmp);
CUtils::write_file(tmp);&
return -3;
strUserID =
pEM-&GetField("user_id");&
bGetUserId =
g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[mysql][simid:%s,&
user_id:%s\r\n",&
strSimID.c_str(),strUserID.c_str() );
printf(tmp);
CUtils::write_file(tmp);&&
&&catch(...)
&& g_connPool.retOneConn(pEM);
//把连接还给连接池
sprintf(tmp,"[mysql] [sim_id:%s& , getUserId
FromMysql& exception**]\r\n",&
strSimID.c_str());
printf(tmp);
CUtils::write_file(tmp);
void CUtils::sendmsg2MQ(&
string&& sMsg)
tmp[1000];
Connection* connection =
g_conFactory-&createConnection();
connection-&start();//创建连接
printf("connect activeMQ& succ\r\n");
Session* session =
connection-&createSession(cms::Session::AUTO_ACKNOWLEDGE
//创建线程
TextMessage* message = session-&createTextMessage(
sMsg );//创建消息
Destination*
destination=NULL;
destination = session-&createQueue( "hongyuanQue"
);//创建队列
MessageProducer*
myproducer=session-&createProducer(destination
myproducer-&setDeliveryMode(
DeliveryMode::NON_PERSISTENT );//消息的持久性
myproducer-&send(message );//发送消息
sprintf(tmp, "send [%s] to activeMQ succ\r\n" ,sMsg.c_str()
printf(tmp);
CUtils::write_file(tmp);
session-&close();
connection-&close();
printf("close a connect to&
activeMQ& succ\r\n" );
&& catch(...)
printf("write&
MQ&& exception**\r\n");
void CUtils::shutdownMQ()
activemq::library::ActiveMQCPP::shutdownLibrary();&
void CUtils::initMQ( string&
strActiveMqIp,& int
nActiveMqPort)&
&& static int nCount_InitMQ =
0;//只初始化一次
&& if(nCount_InitMQ
char& szActiveMqServer[100];
sprintf(szActiveMqServer,&
"tcp://%s:%d",&&
strActiveMqIp.c_str(),& nActiveMqPort);
activemq::library::ActiveMQCPP::initializeLibrary();
g_conFactory =&&
cms::ConnectionFactory::createCMSConnectionFactory(
szActiveMqServer );
if(&g_conFactory == NULL)
sprintf(tmp,"Init ActiveMQ fail** \n");
printf(tmp);
CUtils::write_file(tmp);&
nCount_InitMQ = 1;
&& catch(...)
sprintf(tmp,"Init ActiveMQ exception ** \n");
printf(tmp);
CUtils::write_file(tmp);&
exit(0);&&&&
void& CUtils::initMC(
string&& szMemcachedServer, int
& g_utilConfigMqMcSql.m_strMemcachedIp =
szMemcachedS
& g_utilConfigMqMcSql.m_nMemcachedPort =
CUtils::setMemcached(string&
strKey,& string&
strValue& )
&& char tmp[1000];
char& szMemcachedServerIpPort[100];
sprintf(szMemcachedServerIpPort, "%s:%d",&
g_utilConfigMqMcSql.m_strMemcachedIp.c_str() ,
g_utilConfigMqMcSql.m_nMemcachedPort);
&&&&memcached_server_st
* servers = memcached_servers_parse(szMemcachedServerIpPort);
&&&&memcached_st
* memc = memcached_create (NULL);
&&&&memcached_server_push(memc,
&&&&memcached_server_list_free(servers);
&&&&memcached_behavior_set(memc,
MEMCACHED_BEH***IOR_BINARY_PROTOCOL, 0);
&&&&memcached_return
rc = memcached_set(memc, strKey.c_str (), strlen (strKey.c_str ()),
strValue.data (), strValue.size (), 0, 32);
(rc == MEMCACHED_SUCCESS)
sprintf(tmp,"memcached_set succ! \r\n");
printf(tmp);
CUtils::write_file(tmp);&&&&
&&&&&&size_t
ValueLength = 0;
&&&&&&uint32_t
&&&&&&char
* pValue = memcached_get(memc, strKey.c_str (), strlen
(strKey.c_str ()), & ValueLength, &
flags, & rc);
(rc == MEMCACHED_SUCCESS)
&&&&&&&&&&&
sprintf(tmp,"memcached_get succ! [key=%s , value=%s] \r\n",
strKey.c_str (), pValue);
&&&&&&&&&&&
printf(tmp);
CUtils::write_file(tmp);
&&&&&&&&free
&&&&&&else
sprintf(tmp,"memcached_get fail**& [key =%s]
\r\n", strKey.c_str () );
&&&&&&&&&&&&&
printf(tmp);
&&&&&&&&&&
CUtils::write_file(tmp);&
&&&&&&&&free
sprintf(tmp, "memcached_set error**[Key=%s]\r\n",&
strKey.c_str());
printf(tmp);
CUtils::write_file(tmp);&&&&&
&&&&memcached_free(memc);
&&catch(...)
sprintf(tmp, "memcached_set
exception**[Key=%s]\r\n",& strKey.c_str());
printf(tmp);
CUtils::write_file(tmp);&&&&
&&return 0;
int CUtils::getFromMc(string&
strKey,& string& strValue )
char& szMemcachedServerIpPort[100];
sprintf(szMemcachedServerIpPort, "%s:%d",&
g_utilConfigMqMcSql.m_strMemcachedIp.c_str() ,
g_utilConfigMqMcSql.m_nMemcachedPort);
&&memcached_server_st * servers =
memcached_servers_parse(szMemcachedServerIpPort);
&&memcached_st * memc =
memcached_create (NULL);
&&memcached_server_push(memc,
&&memcached_server_list_free(servers);
&&memcached_behavior_set(memc,
MEMCACHED_BEH***IOR_BINARY_PROTOCOL, 0);
ValueLength = 0;
&&memcached_
&&char * pValue =
memcached_get(memc, strKey.c_str (), strlen (strKey.c_str ()),
& ValueLength, & flags,
&&if (rc ==
MEMCACHED_SUCCESS)
&&&&strValue
&&&&printf("memcached_get
key =% s value =% s \r\n", strKey.c_str (),
strValue.c_str());
&&memcached_free(memc);
&&return 0;
//写日志文件
void CUtils::write_file(char* szContent)
guard(g_mutexWriteFile);
& // 先判断文件是否已经打开
& if(g_fp == NULL)
fopen("tmp.dat",
&&&if(g_fp ==
printf("open log file error**\r\n");
& string strT = CUtils::getY_M_D_H_M_S();
& char szTmp[100];
& //先写当前时间
& sprintf(szTmp, "\r\n [%s] ",
&strT.c_str());
& fwrite(szTmp, strlen(szTmp),1, g_fp);
& fwrite(szContent, strlen(szContent),1,
& fflush(g_fp);
//写日志文件【二进制日志】
void CUtils::write_file_bin(char* pContent, int nLen)
guard(g_mutexWriteFile_Bin);
& // 先判断文件是否已经打开&
&& if(g_fp_bin == NULL)
&&&&g_fp_bin
= fopen("bin.dat",
&&&if(g_fp_bin
printf("open g_fp_bin& error**\r\n");
& string strT = CUtils::getY_M_D_H_M_S();
& char szTmp[100];
& //先写当前时间
& sprintf(szTmp, "[%s]",
&strT.c_str());
& fwrite(szTmp, strlen(szTmp),1, g_fp_bin);
& fwrite(pContent, nLen, 1, g_fp_bin);
& fflush(g_fp_bin);
// a function to become a daemon
void CUtils::InitDaemon()
((pid = fork() ) != 0 )
signal( SIGINT,& SIG_IGN);
&&& signal(
SIGHUP,& SIG_IGN);
&&& signal(
SIGPIPE, SIG_IGN);
&&& signal(
SIGTTOU, SIG_IGN);
&&& signal(
SIGTTIN, SIG_IGN);
&&& signal(
SIGCHLD, SIG_IGN);
&&& signal(
SIGTERM, SIG_IGN);
&&& struct
sig.sa_handler = SIG_IGN;
&&& sig.sa_flags
&&& sigemptyset(
&sig.sa_mask);
&&& sigaction(
SIGHUP,&sig,NULL);
((pid = fork() ) != 0 )
setpgrp();
CUtils::Hex2Ascii(char* pSrcHex, int nSrcLen,&
char* pDstAscii)
&& CHex2Ascii&
&& h2a.Hex2Ascii(
pSrcHex,&&
nSrcLen,&& pDstAscii);
CUtils::setPthreadAtrr(pthread_attr_t&&
thread_attr, size_t& stack_set_size)
&& //保护一下
if(stack_set_size& & 16000)
stack_set_size = 16000;
stack_set_size & 70)
stack_set_size = 70;
&&& size_t
status = pthread_attr_init (&thread_attr);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Create attr", status);
return -1;
status = pthread_attr_setdetachstate (
&thread_attr, PTHREAD_CREATE_DETACHED);
(status != 0)
MYERRMSG("%s, [status:%d] \r\n", "Set detach", status);
return -1;
//通常出现的问题之一,下面的宏没有定义
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
//得到当前的线程栈大小
&&& status =
pthread_attr_getstacksize (&thread_attr,
&stack_size);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Get stack size", status);
return -1;
&&& printf
("Default stack size is %u; minimum is
%u\n",&&&&&&
stack_size,& PTHREAD_STACK_MIN);
//设置栈尺寸
&&& status =
pthread_attr_setstacksize (&
&thread_attr, stack_set_size*1024);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Set stack size", status);
return -1;
//得到当前的线程栈的大小
&&& status =
pthread_attr_getstacksize (&thread_attr,
&stack_size);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Get stack size", status);
return -1;
printf ("new& stack size is %u; minimum is
%u\n",&&&&
stack_size, PTHREAD_STACK_MIN);
&&& return
string& CUtils::getY_M_D_H_M_S()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "%d-d-d d:d:d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday,
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
&& return string(szTmp);
CUtils::getYMDHMS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "�dddd", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday,
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
&& return string(szTmp);
string& CUtils::getY_M_D()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "%d-d-d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday );
string(szTmp);
string& CUtils::getYMD()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "�d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday );
&& return string(szTmp);
string& CUtils::getHH_MM_SS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "d:d:d",&&
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
string(szTmp);&
string& CUtils::getHHMMSS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "ddd",&&
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
string(szTmp);&&
int& CUtils::getFileLen(FILE* fp)
&if(fp == NULL)
&&return -1;
&//获取文件长度
&int iCurPos = ftell(fp);
&fseek(fp,0,SEEK_END);
&int iLen = ftell(fp);
&fseek(fp, iCurPos, SEEK_SET);
& return iL
int CUtils::split(const
string& input, const string&
delimiter,
vector&string&&
results, bool includeEmpties)
&int iPos =
&int newPos =
&int sizeS2 =
(int)delimiter.size();&&
&int isize =
(int)input.size();&&
&if(&( isize == 0
)&||&( sizeS2 == 0
&vector&int&
&newPos = input.find (delimiter,
&if( newPos & 0
&&return 0;
&int numFound =
&while( newPos &= iPos
&&numFound++;&&&positions.push_back(newPos);&&&iPos
&&newPos = input.find (delimiter,
iPos+sizeS2);&&
&if( numFound == 0
)&&{&&&return
&for( int i=0; i &=
(int)positions.size(); ++i
&&if( i == 0 )
input.substr( i, positions[i] );
&&int offset = positions[i-1] +
sizeS2;&&&
&&if( offset &
isize )&&&
&&&if( i ==
positions.size()
input.substr(offset);&&&&
&&&else if( i
= input.substr( positions[i-1] + sizeS2, positions[i] -
positions[i-1] - sizeS2 );&
&&if( includeEmpties || (
s.size() & 0 )
&&&results.push_back(s);&&
&return numF&
三、Hex2Ascii.***件内容
__HEX_TO_ASCII__
#define& __HEX_TO_ASCII__
class& CHex2Ascii
&&CHex2Ascii(){}
&&~CHex2Ascii(){}
&&& //0~9 转为
‘0’~‘9’&&& 10~15
转为 ‘a’~'f'
char& GetAscii(int& n);
//一个字节(16进制)转为2个Ascii字符【一个十六进制的字节,如 0xa7, 高四位是
10,& 低四位是 7, 然后转为 'a'& '7'】
One2Two(char chSrc, char* pDst);
//将16进制转为可显示的 ASCII串,如 0xAA 0xBB 0x8C& 转为ASCII串
“AA BB 8C”
void& Hex2Ascii(char* pSrcHex, int
nSrcLen,& char* pDstAscii);
四、Hex2Ascii.cpp文件内容&
#include &stdlib.h&
#include "hex2ascii.h"
//0~9 转为
‘0’~‘9’&&& 10~15
转为 ‘a’~'f'
char& CHex2Ascii::GetAscii(int&
return& '0' +
&& else if( n&=
return& 'a' + n-10;
&&& return
//一个字节(16进制)转为2个Ascii字符【一个十六进制的字节,如 0xa7,
高四位是 10,& 低四位是 7, 然后转为 'a'&
void CHex2Ascii::One2Two(char chSrc, char* pDst)
&& char& chHigh
= (chSrc && 4)&
&& pDst[0] =
GetAscii(chHigh);
chLow& = (chSrc&0x0f);
&& pDst[1] =
GetAscii(chLow);
//将16进制转为 可显示的 ASCII串,如 0xAA 0xBB
0x8C& 转为ASCII串 “AA BB 8C”
void& CHex2Ascii::Hex2Ascii(char* pSrcHex, int
nSrcLen,& char* pDstAscii)
& if(!pSrcHex || !pDstAscii)
& char pTmp[2];
& for(int i=0; i&nSrcL
&&&One2Two(pSrcHex[i],
&&&pDstAscii[i*3+0]
= pTmp[0];
&&&pDstAscii[i*3+1]
= pTmp[1];
&&&pDstAscii[i*3+2]
&&&pDstAscii[i*3+3]
&五、connPool.h内容如下:
#ifndef __CONNECTION_POOL_H__
#define __CONNECTION_POOL_H__
#include "mutex.h"
MYSQL_CONN_NUM_MAX_VALUE&&
enum _USE_STATUS
&& US_USE = 0,
&& US_IDLE = 1
typedef& struct
_sConStatus
class CConnPool
CConnPool();
~CConnPool();
Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum);//connection& pool
getOneConn();//get a connection
void& retOneConn(void* pMysql);// return a
connection
void& checkConn(); // check the connection if is
createOneConn();
m_szMysqlIp[100];
&& char m_szUser[100];
&& char m_szPwd[100];
&& char m_szDbName[100];
m_nMysqlP&&
CMutex& m_sM
vector&void*&&
map&void*, int& m_mapVI;
map&void*, void*&
m_mapMysqlS
class CConnPoolV2
CConnPoolV2();
~CConnPoolV2();
Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum);//connection& pool
getOneConn(); //从连接池取一个连接
void& retOneConn(void* pConn);//
连接用完了,把它放回连接池。以便其他人用。
void& checkConn(); // check the connection if is
createOneConn();
&& string m_strMysqlIp;
&& string m_strU
&& string m_strP
&& string m_strDbN
m_nMysqlP&
CMutex& m_sM
vector&void*&&
map&void*, int& m_mapVI;
//& 从连接的地址,快速找到索引,便于存放到m_vectorConn中。
六、connPool.cpp内容如下:
#include &stdlib.h&
#include &errno.h&
#include &string.h&
#include &sys/types.h&
#include &netinet/in.h&
#include &sys/socket.h&
#include &sys/wait.h&
#include &arpa/inet.h&
#include &unistd.h&
#include &fcntl.h&
#include &pthread.h&
&iostream&&&&&&&&&&&&&&&&&&&&&&&
#include &memory&
#include &string&
#include &map&
#include &vector&
#include "mysql.h"
#include "encapsulation_mysql.h"
#include "connPool.h"
#include "mutex.h"
using namespace EncapM
CConnPool::CConnPool( )
CConnPool::~CConnPool( )
void* CConnPool::createOneConn()
mysql = mysql_init(0);
if(mysql == NULL)
&& "mysql_init fail**"
&&&&return
if(mysql_real_connect(mysql,& m_szMysqlIp ,
m_szUser ,&&
m_szPwd,&&&
m_szDbName& ,& m_nMysqlPort,
NULL,0)==NULL)
&& "connect failure!"
&&&&&return
&& "connect success!"
CConnPool::Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum)
strcpy(m_szMysqlIp, strMysqlIp.c_str());
&&& strcpy(
m_szUser, strUser.c_str());
strcpy(m_szPwd, strPwd.c_str());
strcpy(m_szDbName, strDbName.c_str());
&&& m_nMysqlPort
= nMysqlP&&
&& m_nConnNum =
&&& for(int i=0;
i&nConnN i++)
&& mysql =
(MYSQL*)this-&createOneConn();
&& if(mysql == NULL)
&& &return
sConStatus* scs = new sConStatus();
scs-&connAddr =
scs-&useStatus = US_IDLE;
m_vectorConn.push_back(scs);&
m_mapVI[scs] =
m_mapMysqlScs[mysql] =
&&m_nConnNum = nConnN
void* CConnPool::getOneConn()
&&& int N =
m_vectorConn.size();
&&for(int i=0; i&
CGuard& guard(m_sMutex);
sConStatus* scs = (sConStatus*)m_vectorConn[i];
if(scs-&useStatus ==&
&&&&&&&&&&
scs-&useStatus = US_USE;
scs-&connA
&&return NULL;
CConnPool::retOneConn(void* pMysql)
& map&void*,
void*&::iterator& it1;
& map&void*,
int&::iterator it2;
& CGuard& guard(m_sMutex);
& it1 = m_mapMysqlScs.find(pMysql);
& if(it1 == m_mapMysqlScs.end())
m_mapVI.find(it1-&second);
& if(it2 == m_mapVI.end())
& int nInx =
& sConStatus* scs =
(sConStatus*) m_vectorConn[nInx];
& scs-&useStatus = US_IDLE;
CConnPool::checkConn()
&& map&void*,
void*&::iterator& it1;
&& MYSQL*&
&& &for(int i=0;
i&m_nConnN i++)
CGuard& guard(m_sMutex);
&& & sConStatus*
scs = (sConStatus*)m_vectorConn[i];
if(scs-&useStatus == US_USE)
&& & mysql
=(MYSQL*)(scs-&connAddr);
status=mysql_query(mysql, "select count(*) from t_" );
&&& if(status !=
0) //说明连接已经不可用了。
it1 = m_mapMysqlScs.find(mysql);
if(it1 != m_mapMysqlScs.end())
m_mapMysqlScs.erase(it1);
mysql_close(mysql);
mysql = (MYSQL*)this-&createOneConn();
m_mapMysqlScs[mysql] =
////////////////////////////// ,
这个类这样写,感觉耦合性更为松散,比较好。使用起来也好理解一些。
CConnPoolV2::CConnPoolV2( )
CConnPoolV2::~CConnPoolV2( )
//创建一个连接,并设为 IDLE状态。
void* CConnPoolV2::createOneConn()
CEncapMysql*& pEM = new CEncapMysql();
if(pEM == NULL)
&printf("pEM ==
NULL**\r\n");&
&return NULL;
int nRet = pEM-&Connect(m_strMysqlIp.c_str(),
m_strUser.c_str(), m_strPwd.c_str());
if(nRet != 0)
&printf("pEM-&Connect
fail**\r\n");&
&return NULL;
pEM-&SetIdle();
return pEM;
&&catch(...)
printf("createOneConn&
exception**\r\n");&
return NULL;
//成功: 返回0
int CConnPoolV2::Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum)
m_strMysqlIp& = strMysqlIp;
m_strUser&&&&
m_strPwd&&&&&
m_strDbName&& = strDbN
&&& m_nMysqlPort
= nMysqlP&&
&& m_nConnNum =
&&& CEncapMysql*
&&& for(int i=0;
i&nConnN i++)
(CEncapMysql*)this-&createOneConn();
& return -1;
m_vectorConn.push_back(pEM);&
m_mapVI[pEM] =
void* CConnPoolV2::getOneConn()
CGuard& guard(m_sMutex);
&&for(int i=0; i&
m_nConnN i++)
CEncapMysql* pEM = (CEncapMysql*)m_vectorConn[i];
if( pEM-&IsIdle())
&&&&&&&&&&
pEM-&SetUsed();
& return pEM;
&&//可能访问MYSQL的用户较多,连接池中已无空闲连接了。只要总连接数没有超限,就新建一个连接。
&&if(m_nConnNum &
MYSQL_CONN_NUM_MAX_VALUE)
CEncapMysql* pEM =
(CEncapMysql*)this-&createOneConn();
& return NULL;
m_vectorConn.push_back(pEM);&
m_mapVI[pEM] = m_nConnNum++;
&&return NULL;
CConnPoolV2::retOneConn(void* pConn)
& map&void*,
guard(m_sMutex);
m_mapVI.find(pConn);
& if(it == m_mapVI.end())
& int nInx = it-&
& CEncapMysql* pEM =
(CEncapMysql*) m_vectorConn[nInx];
& pEM-&SetIdle();
CConnPoolV2::checkConn()
&//暂时可以不实现。因为查询失败时,已重新连接了。
&七、mutex.h的内容如下:
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include &stdlib.h&
#include &string.h&
#include &pthread.h&
#include &iostream&
class CMutex
CMutex() ;
~CMutex() ;
int Lock();
int TryLock();
int UnLock();
pthread_mutex_t &getMutexRef();
& protected:
pthread_mutex_t& m_sM
class CGuard
CGuard(CMutex &mutex);
~CGuard();
&&& CMutex
class CCondition
CCondition();
~CCondition();
wait(CMutex &mutex);
pthread_cond_t m_
///////////////////////////////////////////
class CLock
CLock(){};
&&& virtual
~CLock(){};
//互斥锁: 线程阻塞, 直到获取锁资源. 失败返回-1. 如果不是互斥锁类型,直接返回
&&& virtual int
lock() = 0;
&&& //互斥锁: 释放锁.
失败返回-1. 如果不是互斥锁类型,直接返回
&&& virtual int
unlock() = 0;
&&& //读写锁:
获取读锁资源. 失败返回-1. 如果锁类型不支持读写锁,直接返回.
&&& virtual int
rdlock() = 0;
&&& //读写锁:
获取写锁资源. 失败返回-1. 如果锁类型不支持读写锁,直接返回.
&&& virtual int
wrlock() = 0;
class CMutexLock
CMutexLock(pthread_mutexattr_t* pAttr = NULL);
~CMutexLock();
//互斥锁: 线程阻塞, 直到获取锁资源. 失败返回-1.
return pthread_mutex_lock(&m_lock);
&&& //互斥锁: 释放锁.
失败返回-1
return pthread_mutex_unlock(&m_lock);
&&& //读写锁的方法,
这里只是保持适配
return -1;
&&& //读写锁的方法,
这里只是保持适配
return -1;
pthread_mutex_t& getLock()
pthread_mutex_t& m_
&&& CMutexLock
(const CMutexLock &); //不让拷贝
operator= (const CMutexLock &); //不让赋值
class CRWLock
CRWLock(pthread_rwlockattr_t* pAttr = NULL);
~CRWLock();
//互斥锁的方法, 这里只是保持适配
return -1;
//释放锁资源
return pthread_rwlock_unlock(&m_lock);
&&& //获取读锁资源.
失败返回-1.
return pthread_rwlock_rdlock(&m_lock);
&&& //获取写锁资源.
失败返回-1.
return pthread_rwlock_wrlock(&m_lock);
pthread_rwlock_t& m_
&&& CRWLock
(const CRWLock &); //不让拷贝
operator= (const CRWLock &); //不让赋值
template&typename CLock =
CMutexLock&
class CMutexGuard
CMutexGuard(CLock &lock) : m_lock(lock)
m_lock.lock();
~CMutexGuard()
m_lock.unlock();
protected:
&m_ //引用: 锁
&&& CMutexGuard
(const CMutexGuard&CLock&
&); //不让拷贝构造
operator= (const
CMutexGuard&CLock&&
&); //不让赋值
template&typename CLock =
class CReadGuard : public
CMutexGuard&CRWLock&
&&& //重写构造和析构,
使用读写锁实现
CReadGuard(CLock &rwlock) :
CMutexGuard&CRWLock&(rwlock)
m_lock.rdlock();
~CReadGuard()
m_lock.unlock();
template&typename CLock =
class CWriteGuard : public
CMutexGuard&CRWLock&
&&& //重写构造和析构,
使用读写锁实现
CWriteGuard(CLock &rwlock) :
CMutexGuard&CRWLock&(rwlock)
m_lock.wrlock();
~CWriteGuard()
m_lock.unlock();
八、mutex.cpp的内容如下:
&pthread.h&
#include "mutex.h"
CMutex::CMutex()
& pthread_mutexattr_t& l_sAttr
pthread_mutexattr_init(&l_sAttr);
pthread_mutex_init(&m_sMutex,&l_sAttr);
pthread_mutexattr_destroy(&l_sAttr);
CMutex::~CMutex()
pthread_mutex_destroy(&m_sMutex);
int CMutex::Lock()
return(pthread_mutex_lock(&m_sMutex));
int CMutex::TryLock()
return(pthread_mutex_trylock(&m_sMutex));
int CMutex::UnLock()
return(pthread_mutex_unlock(&m_sMutex));
pthread_mutex_t
&CMutex::getMutexRef()
&&& return
//CGuard实现部分
CGuard::CGuard(CMutex &mutex)
: m_mutex(mutex)
m_mutex.Lock();
CGuard::~CGuard()
m_mutex.UnLock();
//CCondition实现部分
CCondition::CCondition()
pthread_condattr_
pthread_condattr_init(&attr);
pthread_cond_init(&m_cond,
pthread_condattr_destroy(&attr);
CCondition::~CCondition()
pthread_cond_destroy(&m_cond);
int CCondition::wait(CMutex
&&& return
pthread_cond_wait(&m_cond,
&mutex.getMutexRef());
int CCondition::signal()
&&& return
pthread_cond_signal(&m_cond);
CMutexLock::CMutexLock(pthread_mutexattr_t* pAttr )
pthread_mutexattr_init(pAttr);
pthread_mutex_init(&m_lock, pAttr);
pthread_mutexattr_destroy(pAttr);
pthread_mutex_init(&m_lock, NULL);
CMutexLock::~CMutexLock()
pthread_mutex_destroy(&m_lock);
CRWLock::CRWLock(pthread_rwlockattr_t* pAttr )
pthread_rwlockattr_init(pAttr);
pthread_rwlock_init(&m_lock, pAttr);
pthread_rwlockattr_destroy(pAttr);
pthread_rwlock_init(&m_lock, pAttr);
CRWLock::~CRWLock()
pthread_rwlock_destroy(&m_lock);
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

参考资料

 

随机推荐