Odin's Most Misunderstood Feature: `context`

32 points by gingerBill


hc

the post mentions threadlocals being bad solutions. i've hit this issue a number of times, so i'll put in my $0.02:

the biggest but most easily fixed issue is that you can leave the variable set to the wrong thing. you can handle that with RAII/defer, though. just have your bind operation reset it when it goes out of scope.

the main problem with threadlocal is that when you create a new thread, or grab one from a thread pool, or you have some async operation that resumes on a different thread, it breaks in similar ways as a global

Clojure and C# both solve this, with special variables and TaskLocal<T>, respectively. under the hood, those are passing around a copy-on-write context, much like what odin is doing. odin's appears to be less flexible, but saves an indirection or two by hardcoding the set of items instead of making it open ended

and the other main difference is that odin passes it in function calls, while clojure and C# use a threadlocal and has some extra bookkeeping that happens on async boundaries

go also uses this pattern in a lot of places, but you pass the context explicitly. i think doing it implicitly probably solves a lot of problems without much of a perf hit