Last active
June 22, 2016 17:38
-
-
Save caelifer/f4916947fdc69f0524f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - https://play.golang.org/p/mvIHuFmLVV
Output: