By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 811 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Multi-threaded Web Server

P: 3
I'm attempting to write a simple multi-threaded webserver on UNIX that uses a thread pool to handle connections. I use an accept() loop which simply sends requests to a request function, and then sends the requested resource to the client. My server worked fine when it was single-threaded - but when I implement a thread-pool it behaves completely chaotically. The browser displays something different everytime I click refresh. This seems like something I'm doing with threads is not synchronizing properly with how the browser requests resources.

Here is the code:

Expand|Select|Wrap|Line Numbers
  1. The thread pool is defined as:
  2.  
  3. struct server_thread_pool {
  4.       pthread_t* tid;
  5.       int sock_fd;
  6.       volatile uint32_t tcount;
  7.       volatile int8_t wakeup;
  8.       pthread_cond_t cond;
  9.       pthread_mutex_t mutex;
  10. };
  11.  
  12. The accept() loop is:
  13.  
  14.       int client_fd;
  15.       for (;;)
  16.       {
  17.             pthread_mutex_lock(&accept_mutex);
  18.             if (tp.sock_fd = accept(server_sock, (sockaddr*) &m_addr, (socklen_t*)) {
  19.                   pthread_mutex_lock(&tp.mutex);
  20.                   tp.wakeup = TP_WAKEUP;
  21.                   tp.sock_fd = client_fd;
  22.                   pthread_cond_signal(&tp.cond);
  23.                   pthread_mutex_unlock(&tp.mutex);
  24.             }
  25.             else {
  26.                   perror("Web Server Accept");
  27.                   pthread_mutex_unlock(&accept_mutex);
  28.             }
  29.       }
  30.  
  31. And finally, the request thread:
  32.  
  33. void* request_thread(void* thread_pool)
  34. {
  35.       int current_fd;
  36.       server_thread_pool* tp = (server_thread_pool*) thread_pool;      
  37.  
  38.       for(;;) {
  39.             pthread_mutex_lock(&tp->mutex);
  40.             while (tp->wakeup == TP_SLEEP) pthread_cond_wait(&tp->cond, &tp->mutex);
  41.             tp->wakeup = TP_SLEEP;
  42.             current_fd = tp->sock_fd;
  43.             pthread_mutex_unlock(&tp->mutex);
  44.             pthread_mutex_unlock(&accept_mutex);
  45.  
  46.             // PROCESS CLIENT REQUEST
  47.  
  48.             close(current_fd);
  49.       }
  50. }
  51.  
Mar 9 '07 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.