Sometimes it’s necessary to implement a form of “implicit context” to pass a data too cumbersome to pass explicity everywhere. Eg. in slog there’s slog-scope that allows setting a “current logger”, for a duration of a function call. The called code can then retrieve and use that logger even deep down the call stack. It’s not really global variable, though it is implicitly passed around.
Internally this is just implemented as thread-local Vector of objects. https://docs.rs/slog-scope/4.0.1/src/slog_scope/lib.rs.html#102
The problem with this approach is std::thread::spawn looses this information. Any thread spawn inside such a scoped code, will execute with an empty logger.
So it makes me think - it would be great if it would be possible to register some form of a hook that would get executed when std::thread::spawn is called, that would allow slog-scope to initialize thread-local data for a new thread to appear in the same way as it was called inside the original thread.
I guess this would be implemented quite similarily. Rust stdlib would have a global thread-local variable holding Vec of some hooks. When std::thread::spawn is called, it would call all these hooks, so that any code implementing their “implicits” can store and restore the implicit context.
It seems to me the API would actually have to consist of a pair of hooks - one preparing the data from the current thread-local variables, right before spawn, and a second one that would get that data passed as an argument, right after spawn so it can store it in the thread-local variable of the new thread.