Skip to content

Instantly share code, notes, and snippets.

@dlsniper
Created October 14, 2017 08:31
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 dlsniper/4482aebf53330fba6b76c8216077cbf6 to your computer and use it in GitHub Desktop.
Save dlsniper/4482aebf53330fba6b76c8216077cbf6 to your computer and use it in GitHub Desktop.
Go limited worker count
package main
import (
"fmt"
"runtime"
"sync"
)
func doStuff(wg *sync.WaitGroup, guard chan struct{}, id int) {
defer func() {
wg.Done()
<-guard
}()
fmt.Printf("from goroutine %d", id)
}
func main() {
workload := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
guard := make(chan struct{}, runtime.GOMAXPROCS(0))
wg := &sync.WaitGroup{}
for _, id := range workload {
guard <- struct{}{} // would block if guard channel is already filled
wg.Add(1)
go doStuff(wg, guard, id)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment