Last active
March 1, 2018 10:04
-
-
Save urey-hiker/df7aa0664dd126c87d3f5e4e7a27d29a to your computer and use it in GitHub Desktop.
Barrier for concurrency workers to do tasks synchronously.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "sync" | |
type barrier struct { | |
wc int | |
c chan int | |
wg sync.WaitGroup | |
sync.Mutex | |
} | |
func (br *barrier) fence(w int) { | |
id := 0 | |
br.wg.Wait() | |
br.Lock() | |
br.wc++ | |
id = br.wc | |
if id == 1 { | |
br.c = make(chan int) | |
} | |
if id == w { | |
br.wg.Add(1) | |
close(br.c) | |
} | |
br.Unlock() | |
<-br.c | |
if id == w { | |
br.wc = 0 | |
br.wg.Done() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by this article to create barriers for concurrency workers.
The barrier can block workers until all of them ran into br.fence(w).
br.fence can be used multi-times in one worker loop to synchronous several steps, like this: