X hits on this document

PDF document

February 10, 2006 - page 23 / 238





23 / 238



This is fairly straightforward, but it has some problems. What if another more important input comes in while you are waiting for the results of perform_op1()? Now the program will have to handle input in wait_for_op1_results(), too, and somehow return and say something is happening. The loop will then have to somehow handle multiple operations in progress. And this is a simple example, what if there were hundreds of possible inputs, each with their own result handler, and each had to go through several states? You could assign each to a thread, but if you have thousands of possible pending operations in a system, that many threads may thrash your system and render it inoperable, probably right at the time you need it most (since a lot of things are going on).

In an event-driven system, instead you would say:

init() {

<initialize input_data> r e g i s t e r _ f o r _ i n p u t ( o p 1 _ h a n d l e r , i n p u t _ d a t a ) } op1_handler(input_data) { ;

<allocate and initialize op_data> perform_op1(..., op2_handler, op_data); } op2_handler(op_data) {

perform_op2(); <free op_data>


As you see, when you start an operation, you provide the next thing to call when the operation completes. The functions passed around are called “callbacks”. You allocate and pass around chunks of data to be passed to the handlers. And you register input handlers that get called when certain event occurs. So the code runs in short non-blocking sections, registers for the next operation, then returns back to some invisible main loop that handles the details of scheduling operations. This may seem more complicated than the previous example, but it has a large number of advantages:

  • The system is almost always ready to handle input. For instance, user-interface systems (like most widget sets) are almost always event-driven, this makes them much more “live”, since they are always ready to handle user input.

  • This system can handle multiple simultaneous operations without threads. In general, threaded systems are less reliable and more complicated; unless you need priorities or scalability on SMP, why use them? And even if you use them, you can have much better control over what is running in the system with an event-driven system..

  • If you are building a redundant system with data replication, this gives you a natural way to hold your data, know when to transfer it over to the mate system, and continue an operation on the mate system.

  • If you track the data, it’s easy to monitor every operation occuring in the system, stop an operations, or whatever.

Document info
Document views1114
Page views1114
Page last viewedSun Jan 22 17:04:39 UTC 2017