3步解锁本地多人游戏新体验:让Nucleus Co-Op打破设备限制的开源方案

核心内容摘要

开源大模型智能客服实战:如何通过System Prompt设计提升对话精准度
WarcraftHelper:开源工具解决魔兽争霸III兼容性问题与性能优化方案

SQL 中 COUNT 的用法详解

引言在开发高并发网络服务器时,多线程编程是必不可少的技术。

本文将通过一个完整的TCP服务器案例,详细讲解多线程编程中的关键问题:参数传递、内存安全、线程分离等核心技术点,并通过实际代码演示

常见问题的排查与解决方法。

多线程服务器基础架构

1 核心问题:pthread_create的单参数限制pthread_create()函数原型如下:intpthread_create(pthread_t*thread,constpthread_attr_t*attr,void*(*start_routine)(void*),void*arg);关键限制:最后一个参数arg只能传递一个指针,但实际开发中往往需要传递多个参数(如socket文件描述符、客户端地址等)。

解决方案:使用结构体封装多个参数。

2 定义线程参数结构体#includestdio.h#includestdlib.h#includestring.h#includeunistd.h#includepthread.h#includearpa/inet.h#includesys/socket.h// 线程参数结构体typedefstruct{intconnfd;// 客户端连接的文件描述符structsockaddr_inclient_addr;// 客户端地址信息}socket_info;

完整服务器代码实现

1 线程处理函数// 线程回调函数void*client_handler(void*arg){socket_info*info=(socket_info*)arg;charclient_ip[INET_ADDRSTRLEN];// 转换IP地址为可读格式inet_ntop(AF_INET,(info-client_addr.sin_addr),client_ip,INET_ADDRSTRLEN);printf("[线程 %lu] 客户端连接: %s:%d\n",pthread_self(),client_ip,ntohs(info-client_addr.sin_port));// 处理客户端请求charbuffer[1024];ssize_tn;while((n=read(info-connfd,buffer,sizeof(buffer)-

)

{buffer[n]='\0';printf("[线程 %lu] 收到数据: %s",pthread_self(),buffer);// 回显数据write(info-connfd,buffer,n);}printf("[线程 %lu] 客户端 %s:%d 断开连接\n",pthread_self(),client_ip,ntohs(info-client_addr.sin_port));close(info-connfd);free(info);// 释放动态分配的内存returnNULL;}

2 主服务器代码intmain(){intlistenfd,connfd;structsockaddr_inservaddr,cliaddr;socklen_tclilen;pthread_ttid;//

创建socketlistenfd=socket(AF_INET,SOCK_STR

白色连体魅魔内衣套装-白色连体魅魔内衣套装应用

百度百家号客服电话人工服务

123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123 123