This is a creation in Article, where the information may have evolved or changed.
GO Barrier
Barrier is used for synchronization of multiple thread completion states. There are related implementations in the Linux system library, and there are function declarations in pthread.h. There are no related implementations in the standard library of Golang. The following uses the Sync standard library to implement a simple barrier.
Realize
----------$GOPATH/src/barrier/barrier. Go-----------Package Barrierimport ("Sync") type Barrier struct {curcnt int maxcnt int cond *sync. Cond}func newbarrier (maxcnt int) *barrier {mutex: = new (sync. Mutex) Cond: = Sync. Newcond(mutex) return &barrier{curcnt:maxcnt, maxcnt:maxcnt, Cond:cond}}func (Barrier *barrier) barrierwait () {Barr Ier. Cond. L. Lock() if barrier. curcnt--; barrier.curcnt > 0 {Barrier. Cond. Wait()} else {barrier. Cond. Broadcast() barrier. curcnt= Barrier. maxcnt} barrier. Cond. L. Unlock()}
Test
Package Mainimport ("FMT" "Sync" "Barrier") Func main () {FMT. Println("Hello world!") Barrier: = Barrier. Newbarrier(3) VAR wg sync. WaitgroupFor I: =0; i < 3; i++ {Wg. ADD(1) go func () {defer WG. Done() FMT. Println("A") barrier. Barrierwait() FMT. Println("B") barrier. Barrierwait() FMT. Println("C")} ()} WG. Wait()}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.