awelgorithms

Simulate a process with a stack

Updated

Many processes are: suspend work, do inner work, resume. Nested calls, nested loops of collisions, nested HTML. The stack holds the suspended state. Inner work uses the top. Finishing inner pops and resumes.

What to focus on

If you find yourself storing who is waiting in a recursive call, an explicit stack of waiters is the same idea. Draw states as stack snapshots, not as a paragraph.

Worked examples

nested work

s = "(inner)"
  1. push outer
  2. do inner
  3. pop outer and finish

Result: outer waits under inner

sequence

a = [], tasks push A, push B, pop B, pop A
  1. B finishes before A

Result: LIFO completion

two levels

s = "((inner))"
  1. push outer, push mid, finish inner, pop mid, pop outer

Result: two frames wait

Try it

Write simulateFrames(s). s is a nested process written with brackets, or a sequence of push/pop tasks. Push a frame when work is suspended. Pop when inner work finishes. Model '(inner)' as push outer, finish inner, pop outer. Model two nested tasks A then B. Model '((inner))' with two waiting frames.

The process has at least one suspended frame when inner work runs. Nested work is well-bracketed.