From 996819084081c1bf3cc3f9486b570e3112ff3d30 Mon Sep 17 00:00:00 2001 From: nynicg Date: Fri, 10 May 2019 14:57:25 +0800 Subject: [PATCH] barrier pattern --- concurrency/n_barrier/main.go | 141 +++++++++++++--------------------- 1 file changed, 52 insertions(+), 89 deletions(-) diff --git a/concurrency/n_barrier/main.go b/concurrency/n_barrier/main.go index 2957fa5..984e1f7 100644 --- a/concurrency/n_barrier/main.go +++ b/concurrency/n_barrier/main.go @@ -6,40 +6,69 @@ import ( ) type IBarrier interface { + // error for timeout if need Await() error } -type Barrier struct { - cond *sync.Cond - gos uint - curgos uint + +// once +type ChanBarrier struct { + gos int + curGos int + ch chan struct{} + m sync.Mutex } -func NewBarrier(syncGos uint)*Barrier{ - if syncGos < 1{ - panic("min 1") - } - l := &sync.Mutex{} - c := sync.NewCond(l) - return &Barrier{ - cond:c, - gos:syncGos, +func NewChanBarrier(gos int)*ChanBarrier{ + return &ChanBarrier{ + gos:gos, + ch:make(chan struct{}), } } -func (b *Barrier)Await() error{ - b.cond.L.Lock() - defer b.cond.L.Unlock() - b.curgos++ - if b.gos != b.curgos{ - b.cond.Wait() +func (c *ChanBarrier) Await() error { + c.m.Lock() + if c.curGos++;c.gos != c.curGos{ + c.m.Unlock() + <- c.ch }else{ - b.curgos = 0 - b.cond.Broadcast() + c.m.Unlock() + close(c.ch) } return nil } +//type Barrier struct { +// cond *sync.Cond +// gos uint +// curgos uint +//} +// +//func NewBarrier(syncGos uint)*Barrier{ +// if syncGos < 1{ +// panic("min 1") +// } +// l := &sync.Mutex{} +// c := sync.NewCond(l) +// return &Barrier{ +// cond:c, +// gos:syncGos, +// } +//} +// +//func (b *Barrier)Await() error{ +// b.cond.L.Lock() +// defer b.cond.L.Unlock() +// b.curgos++ +// if b.gos != b.curgos{ +// b.cond.Wait() +// }else{ +// b.curgos = 0 +// b.cond.Broadcast() +// } +// return nil +//} + func main(){ @@ -47,7 +76,8 @@ func main(){ wg := &sync.WaitGroup{} gos := 10 wg.Add(gos) - b = NewBarrier(uint(gos)) + //b = NewBarrier(uint(gos)) + b = NewChanBarrier(gos) for i:=0;i