Skip to content

Instantly share code, notes, and snippets.

@ku
Last active March 8, 2020 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ku/2ef2d6eb05c27cde50484edb07d4df36 to your computer and use it in GitHub Desktop.
Save ku/2ef2d6eb05c27cde50484edb07d4df36 to your computer and use it in GitHub Desktop.
barrier
package main
import (
"fmt"
"math/rand"
"time"
)
type Barrier struct {
para chan int
br chan int
items *[]int
f func(int)
}
func NewBarrier(parallelism int, items []int, f func(int)) Barrier {
return Barrier{
make(chan int, parallelism),
make(chan int, 1),
&items,
f,
}
}
func (b Barrier) Wait() {
c := len(*b.items)
for _, i := range *b.items {
func(captured_i int) {
b.Enter()
go func() {
b.f(captured_i)
b.Leave()
}()
}(i)
}
for {
<-b.br
c -= 1
if c <= 0 {
break
}
}
}
func (b Barrier) Enter() {
b.para <- 1
}
func (b Barrier) Leave() {
n := <-b.para
b.br <- n
}
func main() {
items := []int{1, 2, 3, 4, 5, 6, 7, 8 }
b := NewBarrier(4, items, func(i int) {
get(i)
})
b.Wait()
fmt.Printf("quitting pc %d\n", pc)
// <- barrier
}
var pc int = 0
func get(i int) int {
time.Sleep(time.Duration(rand.Intn(800)) * time.Millisecond)
fmt.Printf("%d\n", i)
pc += 1
return 100
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment