Skip to content

Instantly share code, notes, and snippets.

@chrisgoffinet
Created October 2, 2018 16:02
Show Gist options
  • Save chrisgoffinet/767dd533219fbc47979ae1ae9110645b to your computer and use it in GitHub Desktop.
Save chrisgoffinet/767dd533219fbc47979ae1ae9110645b to your computer and use it in GitHub Desktop.
// example of counting semaphore to control fixed no. of goroutines
package main
import (
"fmt"
"time"
)
func main() {
// fixed no. of goroutines that are allowed to run at a time
sema := make(chan struct{}, 5)
for i := 0; i < 100; i++ {
sema <- struct{}{}
go func(i int) {
fmt.Println(i)
time.Sleep(1 * time.Second)
<-sema
}(i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment