When implementing web server, you can create a thread pool to concurrently process HTTP requests from the client. The Code is as follows:
For (I = 0; I <thread_pool_size; I ++) <br/>{< br/> pthread_create (& thread_pool [I], null, (void *) & worker, (void *) I); <br/> pthread_detach (thread_pool [I]); <br/>}
Concurrent thread processing is as follows:
Void * worker (int n) <br/>{< br/> struct server_struct * request; <br/> debugmsg ("worker % d started! ", N); <br/> while (loop) // global variable of" loop "indicates that server is running, if not set, quit <br/>{< br/> pthread_mutex_lock (& pool_mutex); // You shoshould lock mutex before pthread_cond_wait call .. <br/> request = pop_request (); <br/> If (request = NULL) {<br/> // no more jobs, go to sleep now <br/> pthread_cond_wait (& new_request, & pool_mutex); // on pthread_cond_signal event pthread_cond_wai T lock's mutex via pthread_mutex_lock <br/> request = pop_request (); <br/>}< br/> pthread_mutex_unlock (& pool_mutex); // so, you must unlock it. </P> <p> If (request! = NULL) <br/> server (request); <br/> pthread_cond_signal (& thread_free); <br/>}</P> <p> pthread_exit (null ); <br/> return NULL; <br/>}</P> <p> int push_request (struct server_struct * request) <br/>{< br/> int I, added = 0; </P> <p> pthread_mutex_lock (& pool_mutex); <br/> for (I = 0; (I <thread_pool_size )&&(! Added); I ++) <br/>{< br/> If (pool [I] = NULL) <br/>{< br/> pool [I] = request; <br/> added = 1; <br/>}< br/> pthread_mutex_unlock (& pool_mutex); <br/> If (Added) <br/> pthread_cond_signal (& new_request ); <br/> return added; <br/>}</P> <p> struct server_struct * pop_request () <br/>{< br/> int I; <br/> struct server_struct * request = NULL; <br/> for (I = 0; (I <thread_pool_size) & (request = NULL); I ++) <br/> {<Br/> If (pool [I]! = NULL) <br/>{< br/> request = pool [I]; <br/> pool [I] = NULL; <br/>}< br/> return request; <br/>}