previous | start | next

Concurrent Server with Thread Pool

    1   /* 
    2    * echoservert_pre.c - A prethreaded concurrent echo server
    3    */
    4   /* $begin echoservertpremain */
    5   #include "csapp.h"
    6   #include "sbuf.h"
    7   #define NTHREADS  4
    8   #define SBUFSIZE  16
    9   
   10   void echo_cnt(int connfd);
   11   void *thread(void *vargp);
   12   
   13   sbuf_t sbuf; /* shared buffer of connected descriptors */
   14   
   15   int main(int argc, char **argv) 
   16   {
   17       int i, listenfd, connfd, port;
   18       socklen_t clientlen=sizeof(struct sockaddr_in);
   19       struct sockaddr_in clientaddr;
   20       pthread_t tid; 
   21   
   22       if (argc != 2) {
   23           fprintf(stderr, "usage: %s <port>\n", argv[0]);
   24           exit(0);
   25       }
   26       port = atoi(argv[1]);
   27       sbuf_init(&sbuf, SBUFSIZE); //line:conc:pre:initsbuf
   28       listenfd = Open_listenfd(port);
   29   
   30       for (i = 0; i < NTHREADS; i++)  /* Create worker threads */ //line:conc:pre:begincreate
   31           Pthread_create(&tid, NULL, thread, NULL);               //line:conc:pre:endcreate
   32   
   33       while (1) { 
   34           connfd = Accept(listenfd, (SA *) &clientaddr, &clientlen);
   35           sbuf_insert(&sbuf, connfd); /* Insert connfd in buffer */
   36       }
   37   }
   38   
   39   void *thread(void *vargp) 
   40   {  
   41       Pthread_detach(pthread_self()); 
   42       while (1) { 
   43           int connfd = sbuf_remove(&sbuf); /* Remove connfd from buffer */ //line:conc:pre:removeconnfd
   44           echo_cnt(connfd);                /* Service client */
   45           Close(connfd);
   46       }
   47   }
   48   /* $end echoservertpremain */
   49   
   50       <h2>Thread Safety</h2>


previous | start | next