What is event-driven programming?

omegasbk picture omegasbk · Apr 25, 2012 · Viewed 6.9k times · Source

What is event-driven programming and has event-driven programming anything to do with threading? I came to this question reading about servers and how they handle user requests and manage data. If user sends request, server begins to process data and writes the state in a table. Why is that so? Does server stop processing data for that user and start to process data for another user or processing for every user is run in a different thread (multithread server)?

Answer

user1345223 picture user1345223 · Apr 25, 2012

Event driven programming != Threaded programming, but they can (and should) overlap.

Threaded programming is used when multiple actions need to be handled by a system "simultaneously." I use simultaneously loosely as most OS's use a time sharing model for threaded activity, or at least they do when there are more threads than processors available. Either way, not germane to your Q.

I would use threaded programming when I need an application to do two or more things - like receiving user input from a keyboard (thread 1) and running calculations based upon the received input (thread 2).

Event driven programming is a little different, but in order for it to scale, it must utilize threaded programming. I could have a single thread that waits for an event / interrupt and then processes things on the event's occurrence. If it were truly single threaded, any additional events coming in would be blocked or lost while the first event was being processed. If I had a multi-threaded event processing model then additional threads would be spun up as events came in. I'm glossing over the producer / worker mechanisms required, but again, not germane to the level of your question.

Why does a server start processing / storing state information when an event is received? Well, because it was programmed to. :-) State handling may or may not be related to the event processing. State handling is a separate subject from event processing, just like events are different than threads.

That should answer all of the questions you raised. Jonny's first comment / point is worth heeding - being more specific about what you don't understand will get you better answers.