Thread: multithread questions

  1. #1
    Registered User
    Join Date
    Aug 2009

    multithread questions

    Hi I'm really new to threads and trying to use the example from the linux tutorial website

    there code for using threads with server code is.

    /* to compile me in Linux, type:   gcc -o concurrentserver concurrentserver.c -lpthread */
    /* server.c - code for example server program that uses TCP */
    /* From Computer Networks and Internets by Douglas F. Comer */
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <string.h>
    void * serverthread(void * parm);       /* thread function prototype    */
    pthread_mutex_t  mut;
    #define PROTOPORT         5193          /* default protocol port number */
    #define QLEN              6             /* size of request queue        */
    int visits =  0;                        /* counts client connections     */
     Program:        concurrent server
     Purpose:        allocate a socket and then repeatedly execute the folllowing:
                              (1) wait for the next connection from a client
                              (2) create a thread to handle the connection
                              (3) go back to step (1)
                     The server thread will
                              (1) update a global variable in a mutex
                              (2) send a short message to the client
                              (3) close the connection
     Syntax:         server [ port ]
                                port  - protocol port number to use
     Note:           The port argument is optional. If no port is specified,
                            the server uses the default given by PROTOPORT.
    main (int argc, char *argv[])
         struct   hostent   *ptrh;     /* pointer to a host table entry */
         struct   protoent  *ptrp;     /* pointer to a protocol table entry */
         struct   sockaddr_in sad;     /* structure to hold server's address */
         struct   sockaddr_in cad;     /* structure to hold client's address */
         int      sd, sd2;             /* socket descriptors */
         int      port;                /* protocol port number */
         int      alen;                /* length of address */
         pthread_t  tid;             /* variable to hold thread ID */
         pthread_mutex_init(&mut, NULL);
         memset((char  *)&sad,0,sizeof(sad)); /* clear sockaddr structure   */
         sad.sin_family = AF_INET;            /* set family to Internet     */
         sad.sin_addr.s_addr = INADDR_ANY;    /* set the local IP address */
         /* Check  command-line argument for protocol port and extract      */
         /* port number if one is specfied.  Otherwise, use the default     */
         /* port value given by constant PROTOPORT                          */
         if (argc > 1) {                        /* if argument specified     */
                         port = atoi (argv[1]); /* convert argument to binary*/
         } else {
                          port = PROTOPORT;     /* use default port number   */
         if (port > 0)                          /* test for illegal value    */
                          sad.sin_port = htons((u_short)port);
         else {                                /* print error message and exit */
                          fprintf (stderr, "bad port number %s/n",argv[1]);
                          exit (1);
         /* Map TCP transport protocol name to protocol number */
         if ( ((int)(ptrp = getprotobyname("tcp"))) == 0)  {
                         fprintf(stderr, "cannot map \"tcp\" to protocol number");
                         exit (1);
         /* Create a socket */
         sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto);
         if (sd < 0) {
                           fprintf(stderr, "socket creation failed\n");
         /* Bind a local address to the socket */
         if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) {
                            fprintf(stderr,"bind failed\n");
         /* Specify a size of request queue */
         if (listen(sd, QLEN) < 0) {
                            fprintf(stderr,"listen failed\n");
         alen = sizeof(cad);
         /* Main server loop - accept and handle requests */
         fprintf( stderr, "Server up and running.\n");
         while (1) {
             printf("SERVER: Waiting for contact ...\n");
             if (  (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
    	                      fprintf(stderr, "accept failed\n");
                                  exit (1);
    	 pthread_create(&tid, NULL, serverthread, (void *) sd2 );
    void * serverthread(void * parm)
       int tsd, tvisits;
       char     buf[100];           /* buffer for string the server sends */
       tsd = (int) parm;
            tvisits = ++visits;
       sprintf(buf,"This server has been contacted %d time%s\n",
    	   tvisits, tvisits==1?".":"s.");
       printf("SERVER thread: %s", buf);
    So the question I had was just understanding the theory to this. So in the summary it explains it being broken into two parts with the main thread waiting and the server thread dealing with the packets. But just what if the server thread was taking longer and a second packet came to the main thread. Would the main thread create a second server thread or just wait for the first server thread to finish and close? I'm just not sure about the timing issue like what happens if the main thread takes multiple packets will it make multiple server threads or just send all the packets to one single server thread that handles all the packets

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    >> Would the main thread create a second server thread or just wait for the first server thread to finish and close?
    When pthread_create succeeds, a new thread is off and running. You are responsible for either waiting for your threads to finish (pthread_join), or "detach" the threads and call pthread_exit instead of returning from main. If you were to return from main() or call exit() while any of your threads are still running, those threads will die a horrible death. The sample code does neither.

    >> what happens if the main thread [accepts] multiple [sockets], will it make multiple server threads ...
    Yes. You'll have a new and unique thread every time a call to pthread_create succeeds.


  3. #3
    Registered User
    Join Date
    Aug 2009
    okay so if i want to just have 2 threads one for main and one for serverthread how to i send the server thread new packets while its processesing the existing packet or is that even possible. Mainly i wanted the mainthread to send it packets and have the serverthread queue them up and process a packet one at a time so that the serverthread wont really need to pthread_exit until the queue of packets are finished.

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    You would use a producer-consumer queue. Newly accepted sockets are added to the queue in the listening thread. The worker thread then processes each socket in the queue accordingly.

    The queue itself can be an array or linked-list. Then use a pthread condition/mutex to synchronize access to the queue.

    Unfortunately, it's hard to find a correct example code using pthreads....but I found one:


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. A very long list of questions... maybe to long...
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-16-2007, 05:36 AM
  3. Several Questions, main one is about protected memory
    By Tron 9000 in forum C Programming
    Replies: 3
    Last Post: 06-02-2005, 07:42 AM
  4. Trivial questions - what to do?
    By Aerie in forum A Brief History of
    Replies: 23
    Last Post: 12-26-2004, 09:44 AM
  5. questions questions questions.....
    By mfc2themax in forum A Brief History of
    Replies: 1
    Last Post: 08-14-2001, 07:22 AM