一段简单的Linux线程池代码


实现web server时,通过创建一个线程池来并发处理客户端的http请求,代码如下:

  1. for(i = 0; i < THREAD_POOL_SIZE; i++)   
  2. {   
  3.     pthread_create(&thread_pool[i], NULL, (void*)&worker, (void*)i);   
  4.     pthread_detach(thread_pool[i]);   
  5. }  

线程并发处理如下:

  1. void* worker(int n)   
  2. {   
  3.     struct server_struct *request;   
  4.     DebugMSG("Worker %d started!", n);   
  5.     while(loop) // Global variable of "loop" indicates that server is running, if not set, quit   
  6.     {   
  7.         pthread_mutex_lock(&pool_mutex); // You should lock mutex before pthread_cond_wait call..   
  8.         request = pop_request();   
  9.         if (request == NULL) {   
  10.             // No more jobs, go to sleep now   
  11.             pthread_cond_wait(&new_request, &pool_mutex); // On pthread_cond_signal event pthread_cond_wait lock's mutex via pthread_mutex_lock   
  12.             request = pop_request();    
  13.         }   
  14.         pthread_mutex_unlock(&pool_mutex); // so, you must unlock it.   
  15.   
  16.         if(request != NULL)   
  17.             server(request);   
  18.         pthread_cond_signal(&thread_free);   
  19.     }   
  20.   
  21.     pthread_exit(NULL);   
  22.     return NULL;   
  23. }   
  24.   
  25. int push_request(struct server_struct* request)   
  26. {   
  27.     int i, added = 0;   
  28.   
  29.     pthread_mutex_lock(&pool_mutex);   
  30.     for(i = 0; (i < THREAD_POOL_SIZE)&&(!added); i++)   
  31.     {   
  32.         if(pool[i] == NULL)   
  33.         {   
  34.             pool[i] = request;   
  35.             added = 1;   
  36.         }   
  37.     }   
  38.     pthread_mutex_unlock(&pool_mutex);   
  39.     if (added)    
  40.         pthread_cond_signal(&new_request);   
  41.     return added;   
  42. }   
  43.   
  44. struct server_struct* pop_request()   
  45. {   
  46.     int i;   
  47.     struct server_struct *request = NULL;   
  48.     for(i = 0; (i < THREAD_POOL_SIZE)&&(request == NULL); i++)   
  49.     {   
  50.         if(pool[i] != NULL)   
  51.         {   
  52.             request = pool[i];   
  53.             pool[i] = NULL;   
  54.         }   
  55.     }   
  56.     return request;   
  57. }  

相关内容