444www:开启数字时代的无限可能,重塑你的生活边界

核心内容摘要

黄品汇MAB2025安装包:开启您的智慧生活新纪元
张婉莹的初二自愈:一段破茧成蝶的成长诗篇

忍界炽燃:花火与疾风的传说,跨越时空的爱与羁绊

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

本文将通过一个完整的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