高并发服务器多线程服务器.docx
1多线程并发服务器多线程服务器模型在使用线程模型开发服务器时需要考虑以下问题A调整进程最大文件描述符上限B线程如有共享数据,考虑线程同步C服务于客户端线程退出时,退出处理。(退出值,分离态)D系统负载,随着连接客户端增加,导致其它线程不能及时得到CPU2案例说明SERVERC,代码如下/SERVERC/INCLUDEINCLUDEINCLUDEINCLUDEINCLUDEINCLUDE“WRAPH“DEFINEMAXLINE80DEFINESERV_PORT8000STRUCTS_INFO{STRUCTSOCKADDR_INCLIADDRINTCONNFD}VOIDDO_WORKVOIDARG{INTN,ISTRUCTS_INFOTSSTRUCTS_INFOARGCHARBUFMAXLINECHARSTRINET_ADDRSTRLEN/可以在创建线程前设置线程创建属性,设为分离态,哪种效率高内/PTHREAD_DETACHPTHREAD_SELFWHILE1{NREADTSCONNFD,BUF,MAXLINEIFN0{PRINTF“THEOTHERSIDEHASBEENCLOSED\N“BREAK}PRINTF“RECEIVEDFROMSATPORTD\N“,INET_NTOPAF_INET,FORI0ICONNFD,BUF,N}CLOSETSCONNFD}INTMAINVOID{STRUCTSOCKADDR_INSERVADDR,CLIADDRSOCKLEN_TCLIADDR_LENINTLISTENFD,CONNFDINTI0PTHREAD_TTIDSTRUCTS_INFOTS383LISTENFDSOCKETAF_INET,SOCK_STREAM,0BZEROSERVADDRSIN_FAMILYAF_INETSERVADDRSIN_ADDRS_ADDRHTONLINADDR_ANYSERVADDRSIN_PORTHTONSSERV_PORTBINDLISTENFD,STRUCTSOCKADDRLISTENLISTENFD,20PRINTF“ACCEPTINGCONNECTIONS\N“WHILE1{CLIADDR_LENSIZEOFCLIADDRCONNFDACCEPTLISTENFD,STRUCTSOCKADDRTSICLIADDRCLIADDRTSICONNFDCONNFD/达到线程最大数时,PTHREAD_CREATE出错处理,增加服务器稳定性/PTHREAD_CREATEI}CLOSELISTENFDRETURN0}CLIENTC/CLIENTC/INCLUDEINCLUDEINCLUDEINCLUDEINCLUDE“WRAPH“DEFINEMAXLINE80DEFINESERV_PORT8000INTMAININTARGC,CHARARGV{STRUCTSOCKADDR_INSERVADDRCHARBUFMAXLINEINTSOCKFD,NSOCKFDSOCKETAF_INET,SOCK_STREAM,0BZEROSERVADDRSIN_FAMILYAF_INETINET_PTONAF_INET,“127001“,SERVADDRSIN_PORTHTONSSERV_PORTCONNECTSOCKFD,STRUCTSOCKADDRWHILEFGETSBUF,MAXLINE,STDINNULL{WRITESOCKFD,BUF,STRLENBUFNREADSOCKFD,BUF,MAXLINEIFN0PRINTF“THEOTHERSIDEHASBEENCLOSED\N“ELSEWRITESTDOUT_FILENO,BUF,N}CLOSESOCKFDRETURN0}WRAPHIFNDEF__WRAP_H_DEFINE__WRAP_H_VOIDPERR_EXITCONSTCHARSINTACCEPTINTFD,STRUCTSOCKADDRSA,SOCKLEN_TSALENPTRVOIDBINDINTFD,CONSTSTRUCTSOCKADDRSA,SOCKLEN_TSALENVOIDCONNECTINTFD,CONSTSTRUCTSOCKADDRSA,SOCKLEN_TSALENVOIDLISTENINTFD,INTBACKLOGINTSOCKETINTFAMILY,INTTYPE,INTPROTOCOLSSIZE_TREADINTFD,VOIDPTR,SIZE_TNBYTESSSIZE_TWRITEINTFD,CONSTVOIDPTR,SIZE_TNBYTESVOIDCLOSEINTFDSSIZE_TREADNINTFD,VOIDVPTR,SIZE_TNSSIZE_TWRITENINTFD,CONSTVOIDVPTR,SIZE_TNSTATICSSIZE_TMY_READINTFD,CHARPTRSSIZE_TREADLINEINTFD,VOIDVPTR,SIZE_TMAXLENENDIFWRAPCINCLUDEINCLUDEINCLUDEVOIDPERR_EXITCONSTCHARS{PERRORSEXIT1}INTACCEPTINTFD,STRUCTSOCKADDRSA,SOCKLEN_TSALENPTR{INTNAGAINIFNACCEPTFD,SA,SALENPTR0{IFNREADREADFD,PTR,NLEFT0{IFNWRITTENWRITEFD,PTR,NLEFT0{IFNWRITTEN0ELSERETURN1}NLEFTNWRITTENPTRNWRITTEN}RETURNN}STATICSSIZE_TMY_READINTFD,CHARPTR{STATICINTREAD_CNTSTATICCHARREAD_PTRSTATICCHARREAD_BUF100IFREAD_CNT0{AGAINIFREAD_CNTREADFD,READ_BUF,SIZEOFREAD_BUF0{IFERRNOEINTRGOTOAGAINRETURN1}ELSEIFREAD_CNT0RETURN0READ_PTRREAD_BUF}READ_CNTPTRREAD_PTRRETURN1}SSIZE_TREADLINEINTFD,VOIDVPTR,SIZE_TMAXLEN{SSIZE_TN,RCCHARC,PTRPTRVPTRFORN1NMAXLENN{IFRCMY_READFD,IFC \N BREAK}ELSEIFRC0{PTR0RETURNN1}ELSE{RETURN1}}PTR0RETURNN}