A simple Linux thread pool code

Source: Internet
Author: User

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/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.