This article is Senlie original, reprint please retain this address: Http://blog.csdn.net/zhengsenlie
1. After creating a thread pool in the program startup phase, just let the main thread call accept and pass the client connection to an available thread in the pool.
Used to maintain information-based thread structure for each thread typedef struct {pthread_tthread_tid;/* thread ID */longthread_count;/* processing the number of connections */} Thread; thread*tptr;/* the thread structure pointer to an array of thread structures generated with Calloc *///defines a shared array that holds the concatenated socket descriptor descriptors #definemaxncli32intclifd[maxncli], Iget, iput;pthread_mutex_tclifd_mutex;pthread_cond_tclifd_cond;/* include serv08 */#include "unpthread.h" #include " Pthread08.h "static Intnthreads;pthread_mutex_tclifd_mutex = Pthread_mutex_initializer;pthread_cond_tclifd_cond = Pthread_cond_initializer;intmain (int argc, char **argv) {inti, LISTENFD, connfd;voidsig_int (int), thread_make (int); Socklen_taddrlen, Clilen;struct sockaddr*cliaddr;//1. Create a listener socket if (argc = = 3) LISTENFD = Tcp_listen (NULL, argv[1], & Addrlen); else if (argc = = 4) LISTENFD = Tcp_listen (argv[1], argv[2], &addrlen); Elseerr_quit ("usage:serv08" Pr_cpu_time (); for (i = 0; i < nthreads; i++) printf ("Thread%d,%ld connections\n", I, Tptr[i].thread_count); exit (0);} Voidthread_make (int i) {void*thread_main (void *);//Create a thread and make it run the Thread_main function, the only reference to which is the subscript of this thread in an array of thread structures Pthread_ Create (&tptr[i].thread_tid, NULL, &thread_main, (void *) i); return;/* main thread returns */}void *thread_main ( void *arg) {intconnfd;voidweb_child (int);p rintf ("Thread%d starting\n", (int) arg); for (;;) {//Because the CLIFD array is shared by all threads. So call Pthread_mutex_lock and pthread_mutex_unlock to protect Pthread_mutex_lock (&clifd_mutex);//If the two are equal then there is nothing to do, call Pthread_ Cond_wait in sleep on the condition variable, waiting for the main thread to wake while (iget = = iput) pthread_cond_wait (&clifd_cond, &clifd_mutex);// Gets the socket descriptive descriptor to be processed CONNFD = clifd[iget];/* connected socket to service */if (++iget = = maxncli) iget = 0; Pthread_mutex_unlock (&clifd_mutex); tptr[(int) arg].thread_count++;//processing customer requests Web_child (CONNFD);/* Process Request *///Close the connected socket close (CONNFD);}}
UNIX Network Programming Volume 1 server Programming Paradigm 8 pre-create thread, call accept
from the main thread