85-使用多线程改写回射客户端

上一篇文章中,我们已经见识了非阻塞I/O + 缓冲区改写回射客户端的复杂性。本文我们使用多线程来重写客户端,后面可以看到,这个版本要简洁的多。

1. 程序路径

本文使用的程序托管在 gitos 上,你可以使用下面的命令 clone 到你的电脑上:

git clone https://git.oschina.net/ivan_allen/unp.git

如果你已经 clone 过这个代码了,请使用 git pull 更新一下。本节程序所使用的程序路径是 unp/program/nonblockio/mth.

2. 多线程版本客户端设计

既然 writen 函数可能会阻塞,那就把读写 sockfd 这两个操作放到不同线程。下面是伪代码:

void doClient(int sockfd) {   // 创建线程,单独从服务器收数据。   pthread_create(doClientRecv, sockfd);   while(1) {     // 读标准输入     // 发送到服务器(写到 sockfd)   } }  void doClientRecv(int sockfd) {   while(1) {     // 从 sockfd 读     // 写到标准输出   } }

可以看到,程序结构非常简单,下面是比较完整的代码:

void doClient(int sockfd) {       int nr, nw, maxfd, ret, cliclose, totalsend;   char *buf;   pthread_t tid;                   totalsend = 0;                  cliclose = 0;   // 客户端一次发送 Length 字节   buf = (char*)malloc(g_option.length);    assert(buf);                     ret = pthread_create(&tid, NULL, doClientRecv, (void*)sockfd);   if (ret != 0) {     errno = ret;                    ERR_EXIT("pthread_create");   }    while(1) {     nr = iread(STDIN_FILENO, buf, g_option.length);     if (nr < 0) ERR_EXIT("iread from stdin");     else if (nr == 0) {       // client no data to send.             LOG("stdin closed\n");       shutdown(sockfd, SHUT_WR);             break;     }     else {       nw = writen(sockfd, buf, nr);          if (nw < 0) ERR_EXIT("writen to sockfd");       totalsend += nw;     }   }   free(buf);   LOG("send %d totally\n", totalsend);   pthread_join(tid, NULL); }   void* doClientRecv(void *args) {   int nr, length, totalrecv, sockfd = (long)args;   char *buf;    totalrecv = 0;   length = g_option.length;   buf = (char*)malloc(length);   assert(buf);    while(1) {     nr = iread(sockfd, buf, length);     if (nr < 0) ERR_EXIT("iread");     else if (nr == 0) {       LOG("receive %d totally\n", totalrecv);       WARNING("server closed\n");       break;     }     else {       totalrecv += nr;       writen(STDOUT_FILENO, buf, nr);     }   }   free(buf); }

3. 实验及分析

writen 仍然一次写入 1024000 字节的数据,来看看客户端和服务器的运行情况:


这里写图片描述
图1 多线程回射客户端运行情况

从图 1 可以看到,客户端不再有阻塞在 writen 上的情况。程序运行时间与非阻塞版本相比,似乎没有明显的差距,基本上都是在 7.5 到 7.8 秒左右。

4. 总结

多线程版本比非阻塞+缓冲版本要简洁的多,执行效率几乎无异,所以这也是比较推荐的方法。

  • 掌握多线程改写回射客户端的方法

说明:本文转自blog.csdn.net,用于学习交流分享,仅代表原文作者观点。如有疑问,请联系我们删除~