tags:

views:

166

answers:

1

I understand thread driven that Apache uses: every connection opens up a thread and when the response is sent, the thread is closed, releasing the resources for other threads).

But I don't get the event driven design that Nginx uses. I've read some basics about event driven design .. but I don't understand how this is used by nginx to handle web requests.

Where can i read and understand how Nginx is handling the connections in an event driven way so I get why it's better, rather than just accepting that event-based design is better than thread-driven design.

+5  A: 

Nginx uses the Reactor pattern. Basically, it's single-threaded (but can fork several processes to utilize multiple cores). The main event loop waits for the OS to signal a readiness event - e.g. that data is available to read from a socket, at which point it is read into a buffer and processed. The single thread can very efficiently serve tens of thousands of simultaneous connections (the thread-per-connection model would fail at this because of the huge context-switching overhead, as well as the large memory consumption, as each thread needs its own stack).

Onestone
but if one thread can serve tens of thousands of users, why dont use multiple threads to serve more? or am i getting it wrong.
never_had_a_name
Because the reactor has to perform non-threadsafe operations like reading from a socket. Multithreading (a fixed pool of worker threads, e.g. one per CPU) is possible with the Proactor pattern, which works slightly differently - for example the OS places the read data into a buffer for you (you specify the buffer at the start of the asynchronous operation). But the proactor has its own disadvantages - it has to reserve more memory for buffers; it is also slower on Linux when only using a single CPU.
Onestone