Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

CyclicBarrier golang implementation

License

NotificationsYou must be signed in to change notification settings

marusama/cyclicbarrier

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AwesomeBuild StatusGo Report CardCoverage StatusGoDocLicense

CyclicBarrier is a synchronizer that allows a set of goroutines to wait for each other to reach a common execution point, also called a barrier.

Inspired by Java CyclicBarrierhttps://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CyclicBarrier.html and C# Barrierhttps://msdn.microsoft.com/en-us/library/system.threading.barrier(v=vs.110).aspx

Usage

Initiate

import"github.com/marusama/cyclicbarrier"...b1:=cyclicbarrier.New(10)// new cyclic barrier with parties = 10...b2:=cyclicbarrier.NewWithAction(10,func()error {returnnil })// new cyclic barrier with parties = 10 and with defined barrier action

Await

b.Await(ctx)// await other parties

Reset

b.Reset()// reset the barrier

Simple example

// create a barrier for 10 parties with an action that increments counter// this action will be called each time when all goroutines reach the barriercnt:=0b:=cyclicbarrier.NewWithAction(10,func()error {cnt++returnnil})wg:= sync.WaitGroup{}fori:=0;i<10;i++ {// create 10 goroutines (the same count as barrier parties)wg.Add(1)gofunc() {forj:=0;j<5;j++ {// do some hard work 5 timestime.Sleep(100*time.Millisecond)err:=b.Await(context.TODO())// ..and wait for other parties on the barrier.// Last arrived goroutine will do the barrier action// and then pass all other goroutines to the next roundiferr!=nil {panic(err)            }        }wg.Done()    }()}wg.Wait()fmt.Println(cnt)// cnt = 5, it means that the barrier was passed 5 times

For more documentation seehttps://godoc.org/github.com/marusama/cyclicbarrier


[8]ページ先頭

©2009-2025 Movatter.jp