4 ms·
I'm glad I'm not the only one who noticed a context is basically a form of dynamic scoping, but with a tendency towards weaker type guarantees. Dynamic scope is
by zbobet2012 7y ago
I'm glad I'm not the only one who noticed a context is basically a form of dynamic scoping, but with a tendency towards weaker type guarantees. Dynamic scope is incredibly useful for cross-cutting concerns. However, I implemented this but found several problems in practice I've never reconciled.
The two big issues where:
1) "User managed" namespaces
2) Multi-process programs, or perhaps multi scope programs
The issue with "user-managed" namespaces is basically one of lexical scoping. In traditional dynamic scope, all variables in the dynamic scope are global. As such people tend to accidentally overwrite other people's variables. I've thought through some ways around this, but none have been elegant.
The more important, and foundational one takes some explaining. Consider some code:
type Work struct {
Ctx context.Context
Result chan<- int
}
func NewWork(ctx context.Context, c chan<- int) *Work {
return &Work{
Ctx: ctx,
Result: c,
}
}
type Worker struct {
c <-chan *Work
}
func NewWorker(c <-chan *Work) {
return &Worker{
c: c,
}
}
func (w *Worker) Work(ctx context.Context) {
for work := range w.c {
// We now have two contexts,
// the context of the work call, and
// our "local" context"
// Both are usefull!
}
}
func main() {
workers := make([]*Worker, 0, 10)
workChan := make(chan *Work, len(workers))
for i, _ := range workers {
workerContext := context.Default()
workers[i] = NewWorker(workChan)
go w.Work(workerContext)
}
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
httpContext := context.Default()
work := NewWork(ctx, result)
fmt.Fprintf(w, "Got Result, %q", <-result)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
As we can see in the work function above, context is more than just your function chain. Now arguably dynamic scope doesn't need to handle this, but it is very commonly the case in CSP/etc. based languages our most relevant scope does not come from dynamic scope.