On this page:

9 Lab Modeling Event Loops


developing a model of event loops, like those for JS

Justin P. and Shriram K. developed and presented a model of JavaScript’s event loop.

Our model deals with two kinds of events:
  • key events happen when the user presses a key, and

  • a resume event returns execution to running a thread.

These are assumed to happen in chunks, with time in between each chunk; for instance, the user may type ‘h’ ‘i’, wait a while, and then type ‘w’ ‘o’ ‘r’ ‘l’ ‘d’. We choose to represent such sequences as lists of lists. In particular, the example is represented as

(((key "h") (key "i")) ((key "w") (key "o") (key "r") (key "l") (key "d"))).

(This is a modelling choice; there are many other sensible choices.)

Since it is important that key events get processed eventually, a resume event forces a process to yield and allow other events to be processed. In the Redex model, this is represented by pushing a resume event onto the end of the current chunk.


Exercise 18. Download the event loop Redex model. Try running the examples: (traces event-loop-> t-event{1,2,3,4}), or write your own example and view its trace. Read the e-event and e-yield reductions in the Redex model, and see if you can make sense of them. image

Exercise 19. This event loop allows starvation; This exercise is due to Sorawee Porncharoenwase. that is, if the resume thread runs forever, then the next chunk of key events will never be processed, even if resume yields infinitely often. Can you fix this?

Note This question is open-ended. There is an easy fix, and there are fixes that suggest interesting implementations. image