Created
July 10, 2016 15:34
-
-
Save mdouchement/77b45c0b99d71781a63770a4e8153e7e to your computer and use it in GitHub Desktop.
Goroutine rate limiter
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 ( | |
"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