Simple Web server--tinywebserver implemented with thread pooling
Write a simple Web server using thread pool implementation, mainly can review IO multiplexing, thread pool, signal, finite state machine, HTTP protocol parsing and other content.
The following first gives the implementation of the problem encountered in the process and the solution, and then give the project specific code, code is based on "Linux high-performance server Programming" written.
0 function and IO model
Function: A concurrent Web server implemented using the thread pool, capable of resolving HTTP GET requests, and using browser access to return the corresponding content.
IO Model: Using reator Mode (event-driven + non-blocking IO) + thread pool . The Epoll loop is used for event notifications, and if LISTENFD is readable, call accept to join the newly created FD to the Epoll routine, and if it is a connected FD, join it to the producer-consumer queue to perform the task by the worker thread.
1 Why use a thread pool? Specific implementation of the thread pool?
1) When a multi-process calls the fork function, although the address space is copied at write time, but need to replicate the parent process's page table (csapp-p584), the cost is large, threading can solve the problem of fork overhead, but the scheduler and memory problems still cannot be solved, so the thread pool, the number of threads fixed. Can solve the above problem. Because the TCP connection is a long connection, read reads will wait until the data is read, causing blocking, so it is set to non-blocking.
2) thread pool implementation: Use C + + to encapsulate a thread pool class, roughly creating a fixed number of threads (like the number of cores), and then maintaining a producer-consumer queue (with mutexes and semaphore) within the class. Provides the appropriate processing functions for adding tasks (producers) and performing tasks (consumers).
Where the mutex mutex ensures that the queue is full do not continue to press, the queue is empty when the task operation, Semaphore guarantee synchronization, only one thread at a time to execute the queue read and write operations.
Simple Web server--tinywebserver implemented with thread pooling