12.37

see origin tiny server in section 11.6 on book

the key is how to pass connfd into thread

--- 12.tiny.c	2021-02-25 07:26:33.305926066 +0000
+++ 12.37.c	2021-02-25 07:26:33.302592754 +0000
@@ -13,9 +13,13 @@
 void clienterror(int fd, char *cause, char *errnum,
     char *shortmsg, char *longmsg);
 
+void *thread(void *vargp);
+
 int main(int argc, char **argv)
 {
   int listenfd, connfd;
+  int *connfdp;
+  pthread_t tid;
   char hostname[MAXLINE], port[MAXLINE];
   socklen_t clientlen;
   struct sockaddr_storage clientaddr;
@@ -35,11 +39,23 @@
     Getnameinfo((SA *) &clientaddr, clientlen, hostname, MAXLINE,
         port, MAXLINE, 0);
     printf("Accepted connection from (%s, %s)\n", hostname, port);
-    doit(connfd);                                             //line:netp:tiny:doit
-    Close(connfd);                                            //line:netp:tiny:close
+
+    connfdp = (int*)Malloc(sizeof(int));
+    *connfdp = connfd;
+    Pthread_create(&tid, NULL, thread, connfdp);
   }
 }
 
+void *thread(void *vargp) {
+  int connfd = *(int*)vargp;
+  Pthread_detach(Pthread_self());
+  Free(vargp);
+
+  doit(connfd);
+  Close(connfd);
+  return NULL;
+}
+
 /*
  * doit - handle one HTTP request/response transaction
  */

run server

(cd ./site/content/chapter12/code; make && ./12.37)

open another terminal and benchmark it

wrk -d4 http://localhost:5000

output

Running 4s test @ http://localhost:5000
  2 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    60.24ms   87.59ms 354.24ms   82.32%
    Req/Sec   481.88    276.48     1.09k    66.67%
  3151 requests in 4.10s, 704.67KB read
Requests/sec:    768.63
Transfer/sec:    171.89KB
comments powered by Disqus