#include "common.h" #include "pool.h" #define NTHREADS 4 #define SBUFSIZE 16 void toggle(int conn_sock,int hit); void *serve_client(void *vargp); void toggle(int conn_sock,int hit) { size_t n; int i,no=0; char buf[MAXLINE]; //printf("线程%d服务第%d个客户请求通信开始\n",tid,hit); while((n =recv(conn_sock, buf, MAXLINE,0))> 0) { printf("toggle服务器收到第%d个客户第%d个消息,长度为%d字节\n", hit,++no,(int)n); for(i=0; i\n", argv[0]); exit(1); } listen_sock = open_listen_sock(port); if( listen_sock==-1) { printf("端口号%d繁忙\n",port); exit(1); } port = atoi(argv[1]); listen_sock = open_listen_sock(port); if( listen_sock==-1) { printf("端口号%d繁忙\n",port); exit(1); } printf("start main\n"); // 初始化线程池 threadpool* pool = initThreadPool(NTHREADS); // 创建示例任务并将其添加到线程池 for (hit=1; ; hit++) { conn_sock = accept(listen_sock, (SA *) &clientaddr, &clientlen); /* determine the domain name and IP address of the client */ hp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); haddrp = inet_ntoa(clientaddr.sin_addr); //printf("server connected to %s (%s)\n", hp->h_name, haddrp); task* new_task = (task*)malloc(sizeof(task)); new_task->function = handle_request; // 假设任务函数为 toggle new_task->taskid = hit; // 任务参数,假设为 socket fd 或其他参数 new_task->sock=conn_sock; addTaskToThreadPool(pool, new_task); /* Insert conn_sock in task pool */ } // 等待线程池中的所有任务执行完毕 waitThreadPool(pool); // 销毁线程池 destroyThreadPool(pool); printf("stop main\n"); return 0; }