Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active June 22, 2016 17:38
Show Gist options
  • Save caelifer/f4916947fdc69f0524f6 to your computer and use it in GitHub Desktop.
Save caelifer/f4916947fdc69f0524f6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
cb := NewCB(5)
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
name := fmt.Sprintf("task #%d", id+1)
for b := 0; b < 2; b++ {
fmt.Printf("%s is waiting at the barrier #%d.\n", name, b+1)
cb.Await()
fmt.Printf("%s has crossed the barrier #%d.\n", name, b+1)
}
}(i)
}
wg.Wait()
}
type cb struct {
sync.Mutex
p int
n int
b chan struct{}
}
func (cb *cb) reset() {
cb.Lock()
defer cb.Unlock()
cb.n = cb.p
close(cb.b)
cb.b = make(chan struct{})
}
func (cb *cb) Await() {
cb.Lock()
cb.n--
n := cb.n
b := cb.b
cb.Unlock()
if n > 0 {
<-b
} else {
fmt.Println("All parties have arrived to the barrier, lets play...")
cb.reset()
}
}
func NewCB(parties int) *cb {
cb := &cb{
p: parties,
n: parties,
b: make(chan struct{}),
}
return cb
}
@caelifer
Copy link
Author

caelifer commented Nov 6, 2015

Live code - https://play.golang.org/p/mvIHuFmLVV

Output:

task #5 is waiting at the barrier #1.
task #1 is waiting at the barrier #1.
task #2 is waiting at the barrier #1.
task #3 is waiting at the barrier #1.
task #4 is waiting at the barrier #1.
All parties have arrived to the barrier, lets play...
task #4 has crossed the barrier #1.
task #4 is waiting at the barrier #2.
task #3 has crossed the barrier #1.
task #3 is waiting at the barrier #2.
task #5 has crossed the barrier #1.
task #5 is waiting at the barrier #2.
task #1 has crossed the barrier #1.
task #1 is waiting at the barrier #2.
task #2 has crossed the barrier #1.
task #2 is waiting at the barrier #2.
All parties have arrived to the barrier, lets play...
task #2 has crossed the barrier #2.
task #1 has crossed the barrier #2.
task #4 has crossed the barrier #2.
task #3 has crossed the barrier #2.
task #5 has crossed the barrier #2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment