gobyexample
gobyexample copied to clipboard
Proposal: Adding example on Condition Variables
Would you be open to having a page on Condition Variables, i.e. sync.Cond
? It could go right after the mutex page and I believe it'd be a great resource since neither the go tour nor the docs have good examples/motivation on this synchronization primitive.
I'd be happy to contribute with a PR, but I thought I might ask before devoting the time to it in case the feature is considered too advanced for the tutorial.
And thanks for maintaining such a high quality learning resource!
Not objecting per se, but do note that sync.Cond
is considered a very specialized tool in Go. I'd venture to say that it's not very widely used, given that Go has channels. See the discussion at https://github.com/golang/go/issues/20491 about the difficulty of finding an idiomatic example for its use.
I'm open to this, but I don't think I've ever used sync.Cond
in my own Go code, so I'm not sure what a good example would be, or even that there are good examples for this level of documentation. Do you want to share a specific idea for an example and we can discuss from there? Unfortunately I can't promise if it will or won't be too advanced without seeing something specific (:
I've used sync.Cond
in scenarios where one routine needs to wake up N
awaiting routines where N
is unknown to the waker routine. With channels I've not found an easy way to keep waking routines without blocking the waker.
A concrete example where I've found it very idiomatic is for woker-coordinator communication where there are sequential phases of computation, for example Map Reduce.
E.g. Coordinator has both map tasks and reduce tasks, reduce tasks can only run after all map tasks are done. In this scenario workers can ask the coordinator for a task and if no more map tasks are available then the worker waits on a condition variable. Once the coordinator knows all map tasks are complete it broadcasts on the condition variable so awaiting workers can be assigned a reduce task.
My guess is that the scenario can be distilled into a more succinct example, but it'd be great to hear your thoughts first.
@JJGO if you haven't seen it, I recommend checking out Bryan Mill's Rethinking Classical Concurrency patterns. The slides with speaker notes are at https://drive.google.com/file/d/1nPdvhB0PutEJzdCq5ms6UI58dp50fcAN/view -- start on page 37 for cond vars; you can also find a video of the talk online.
Bryan takes a fairly esoteric view on what are pretty common synchronization primitives. +1 to a sync.Cond example, but be careful! :)