Go: Monitor Pattern
Published in
4 min readAug 10, 2019
Go implements the monitor pattern thanks to the sync
package and the sync.Cond
structure. The monitor pattern allows our goroutines to wait for a specific condition while entering in a sleeping mode without blocking our execution or consuming resources.
Condition variable in action
Let’s start with an example of this pattern in order to see the advantages it could bring. I will use the example provided in the presentation by Bryan Mills :
The queue is a pretty simple structure composed by an internal array of items and sync.Cond
structure. Then, we do two things:
- Ten goroutines are launched and will try to consume X items in a row. If those items are not all available at once, the goroutine will wait to be woken up
- The main goroutine will fill the queue up with one hundred items. For each item added, it will wake up one of the goroutines that is waiting for items.
Here is the output of this program:
4: [31 32 33 34]
8: [10 11 12 13 14 15 16 17]
5: [35 36 37 38 39]
3: [ 7 8…