ajeeb icon indicating copy to clipboard operation
ajeeb copied to clipboard

Nuanced en masse cancellation

Open nasser opened this issue 4 years ago • 0 comments

When restarting a game it is useful to be able to get rid of any background coroutines while preserving the "main" coroutine. It's important to do this in a way that does not enshrine the "main" coroutine in any way.

One possible approach is to take advantage of the ordered nature of schedules. If coroutine B is farther in the schedule than coroutine A then B guaranteed to have started later than A. If we want to get rid of any coroutines started after a coroutine, we could expose a removeAllAfter(i) method, where i is the offset into the schedule after which to remove coroutines.

SCHED.add(function* () { // "main" coroutine
  const depthAtStart = SCHED.size  // or similar
  while(true) {
    // ... coroutine body
    // when resetting
    SCHED.removeAllAfter(depthAtStart)
  }
})

removeAllAfter should call return() on the relevant coroutines and allow them to be cleaned up in later ticks.

nasser avatar Dec 12 '21 00:12 nasser