by captainmuon · 9y ago · 0 comments
A (not very good) example in pseudocode would be:
complicated_operation(param) with context (log_out=myfile);
// complicated_operation calls a function,
// that calls another function...
void log(string str) context (File log_out=stdout) {...};
This would be a bit like TLS, but has the advantage that the context reverts after the original call.Usually, when I have this problem, I just stuff all the functions into a class, and make the "context" private fields. But then you end up with classes that really "don't want to" be classes, the lifetime of the context state is longer than necessary and unclear, and it feels like a hack. Also, in many languages going from free functions (and plain data and closures) to classes takes a bit of rewriting due to different syntax.
The only language I'm aware of that has these "dynamic scopes" is (apparently) Emacs Lisp, but it should be possible to fake them in C++ quite well.
It would also make the situation in the article a lot cleaner, IMO.
using(TransactionScope scope = new TransactionScope()){
//do stuff
}
Any connection created while that block is active will 'enlist' in the transaction associated with that scope. This works (I think...can't find it now) by using something called 'CallContext', which is more or less a static key-value store that's persisted up and down the call stack (including through async continuations, not sure how that works).If the 'CallContext' is static, doesn't that mean it's global and shared between threads? Well...in C# that's not necessarily true since the thread is accessible via a static property and it's possible to store data against the thread (which is exactly what 'CallContext' does, plus some magic that moves the data during async continuations in case the execution thread changes)
> but it should be possible to fake them in C++ quite well.
Been there done that; had a dynamic_var<T> template some seventeen year ago. It provided thread-specific rebinding and all.
(call-with-dynamic-bind ((var1 val1)(var2 val2)...) stuff...)
It lets you introduce dynamically scoped variables that work pretty much the way you described.
(There is a dynamic binding operator called progv, but the situation for that is when the variable names are computed.)
So dynamically scoped contexts are achieved just by binding these special variables. By convention, they are usually given names beginning and ending with an asterisk ("earmuffs") to put them into an effectively separate namespace.
That parametrize is reminiscent of fluid-let; another Scheme hack to simulate dynamic scope.