GO leverages sync Library for Barrier

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.