2 ms·
I generally prefer Lisp-style ✲dynamic✲ variables. They basically work the same way singletons do, but they can be set and reset at a block-scoped level (great
by pcwalton 14y ago
I generally prefer Lisp-style ✲dynamic✲ variables. They basically work the same way singletons do, but they can be set and reset at a block-scoped level (great for test mocks and the like, and makes your control flow easier to understand), and they play much better with threads.
Rust doesn't even have singletons or global variables, since they aren't threadsafe. It has thread-local storage, which dynamic variables are built on top of.
- masklinn 14y ago> It has thread-local storage, which dynamic variables are built on top of. That hack only works if execution can never be suspended though. The issue exists in Python where it's possible to fake dynamic scope using threadlocals, but that can blow up if execution is suspended (between `yield`s in a generator, for instance) as the stack doesn't get unwound (merely frozen) and the threadlocal isn't reverted if it's in the frozen part of the stack. Same deal if it's possible to unshift stack frames, the threadlocal will more than likely end up in the wrong state. An other thing which bothers me with threadlocals is that it's not really possible to introspect currently-bound locals in order to "save" them alongside lambdas (though that may be an API issue more than an issue with the locals themselves), and in my experience async callbacks tend to need their creation stack context more than their callstack context.
- pcwalton 14y agoBoth good points. Rust doesn't have the problem with execution being suspended, since the only mechanism for suspending execution is through the task system. Thread locals are all per-task. The issue with introspection is fair, and it's a gotcha you have to keep in mind whenever you use dynamic variables. They're necessary to make the task system and condition handler system work under the hood, however, so we can't just remove them.
- masklinn 14y ago> They're necessary to make the task system and condition handler system work under the hood, however, so we can't just remove them. Oh I've nothing against dynamic variables at all and wouldn't want them (or conditions) to be removed from Rust (in fact I wish solid dynamic variables were available in more languages), don't get me wrong.