r/ProgrammingLanguages • u/mttd • Mar 31 '26
From error-handling to structured concurrency
https://blog.nelhage.com/post/concurrent-error-handling/
20
Upvotes
r/ProgrammingLanguages • u/mttd • Mar 31 '26
View all comments
3
u/phischu Effekt Mar 31 '26
Thank you for this valuable resource. Based on it, I have implemented some of the ideas in Effekt, you can try them online.
What if we always waited on tasks?
We define an effect
createthat allows us to spawn a task with a result of typeA.A task is box that has only access to the resources
io,async, andglobal. Boxes are mechanism that is distinct from effects.We then define a handler
launcherthat handles thecreateeffect by creating a promise for the task, then resuming, then awaiting.It returns a list of all results when all created tasks are done.
I hate to cancel, but…
Now we define an effect
cancelthat never returns, and an effectyield, that itself uses thecanceleffect to signal cancellation.As a user or library author we will have to strategically insert yield points into our program.
We handle
cancellationwith a global reference that we set totruewhen the program usescancel.When the program yields we check if cancellation happened, and either raise
cancelat the call-site ofyield, or resume normally.A tree of tasks with cancellation
We combine these two ideas with a new effect
startthat starts a task that can be cancel the other tasks and itself be cancelled at yield points.The
concurrencyhandler uses thelauncherto make sure we wait for all tasks to finnish, creates a shared global mutable reference, and handles cancellation of each started task.It returns a list of the results of those tasks that weren't cancelled.
Finally an example
To try our new toy library, we start two tasks that print, sleep, yield, and one of them cancels the other one.
It prints
and we encourage you to experiment with it in our online playground.