Skip to content

Instantly share code, notes, and snippets.

@mdouchement
Created July 10, 2016 15:34
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 mdouchement/77b45c0b99d71781a63770a4e8153e7e to your computer and use it in GitHub Desktop.
Save mdouchement/77b45c0b99d71781a63770a4e8153e7e to your computer and use it in GitHub Desktop.
Goroutine rate limiter
package main
import (
"fmt"
"sync"
"time"
)
// limiter is a counting semaphore for limiting concurrency in action function.
var limiter = make(chan struct{}, 4)
func action(i int) {
limiter <- struct{}{}
defer func() { <-limiter }()
fmt.Println("Perform action:", i)
time.Sleep(4 * time.Second)
}
// ===================================
func main() {
var n sync.WaitGroup
for i := 0; i < 12; i++ {
n.Add(1)
go func(i int) {
defer n.Done()
action(i)
}(i)
}
n.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment