Skip to content

Instantly share code, notes, and snippets.

@theverything
Created June 7, 2019 16:51
Show Gist options
  • Save theverything/ae1a2b803514e630dc68ee5be6d99573 to your computer and use it in GitHub Desktop.
Save theverything/ae1a2b803514e630dc68ee5be6d99573 to your computer and use it in GitHub Desktop.
concurrent work with throttling
package main
import (
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
)
const things = 10
func main() {
var wg sync.WaitGroup
c := make(chan string, things)
r := make(chan struct{}, 2)
st := time.Now()
for i := 0; i < things; i++ {
wg.Add(1)
log.Printf("waiting %v / %v in queue", i, len(r))
r <- struct{}{}
go func(x int) {
defer wg.Done()
defer func() {
<-r
log.Printf("done %v / %v in queue", x, len(r))
}()
// do some work
log.Printf("working %v / %v in queue", x, len(r))
time.Sleep(1 * time.Second)
c <- strconv.Itoa(x)
}(i)
}
wg.Wait()
close(c)
close(r)
d := time.Since(st)
n := make([]string, 0, len(c))
for j := range c {
n = append(n, j)
}
fmt.Printf("\ntook %v / %s", d, strings.Join(n, ", "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment