Version 1 of Threads vs. events

Updated 2001-10-11 13:24:56

The following came from the not uncommon Question/Answer pair

   Q: I Want Threads
   A: You Have An [Event] Loop

mailto:[email protected] (Uwe Klein) wrote in the comp.lang.tcl newsgroup:

Your answer says only that tcl has an event loop, but gives no explamation as to the differences / advantages.

1st Try:

POLLED

see if any in a list of jobs have to be done and process them. loop till dead.

THREAD

In a threaded program one will do each "primitive" loop of action in its own thread.

 thread1 { block in read ; read file ; process read ; 
                                signal whats been done }
 thread2 { block on user input ; process user input ; 
                                signal for crt update  }
 thread3 { ...

Where threads interact they have to be synced somehow.

EVENT

In event-oriented programming one will set up an event handler for anything that should / will happen.

 event1 { fileevent readable datafile { do what must be done 
                        i.e. put data into dataarray } }
 event2 { writing to dataarray { compute depending values } }
 event2a { writing to dataarray { update crt } }
 event3 { button EXIT { clean up and exit }
 event4 { ...

Generated events are queued and then processed by the event loop.

If all dependencies are described correctly through "trace variable" , "fileevent", "widget -command" , .. any internal/external stimulus will cascade down its described dependecies. Think of an event-looped program as something equivalent to a Makefile for your functional requirements.

Caveat: if your code contains "computing monoblocs" your program becomes unresponsive.


Arts and crafts of Tcl-Tk programming