Golang 中的回环栅栏

alfred-zhong ·
type Barrier struct { mu sync.RWMutex cond *sync.Cond c int n int f bool } func NewBarrier(workers int) *Barrier { b := &Barrier{n: workers} b.cond = sync.NewCond(b.mu.RLocker()) return b } func (self *Barrier) Before() { self.mu.Lock() self.c++ if self.c == self.n { self.f = true self.cond.Broadcast() } self.mu.Unlock() self.mu.RLock() for !self.f { self.cond.Wait() } self.mu.RUnlock() } func (self *Barrier) After() { self.mu.Lock() self.c-- if self.c == 0 { self.f = false self.cond.Broadcast() } self.mu.Unlock() self.mu.RLock() for self.f { self.cond.Wait() } self.mu.RUnlock() }
#1
更多评论
type Barrier struct { mu sync.RWMutex cond *sync.Cond c int n int f bool } func NewBarrier(workers int) *Barrier { b := &Barrier{n: workers} b.cond = sync.NewCond(b.mu.RLocker()) return b } func (self *Barrier) Before() { self.mu.Lock() self.c++ if self.c == self.n { self.f = true self.cond.Broadcast() } self.mu.Unlock() self.mu.RLock() for !self.f { self.cond.Wait() } self.mu.RUnlock() } func (self *Barrier) After() { self.mu.Lock() self.c-- if self.c == 0 { self.f = false self.cond.Broadcast() } self.mu.Unlock() self.mu.RLock() for self.f { self.cond.Wait() } self.mu.RUnlock() } func worker(b *Barrier, c *counter, wg *sync.WaitGroup) { for i := 0; i < 3; i++ { b.Before() c.Incr() b.After() fmt.Println(c.Get()) } wg.Done() }
#2