Created
October 14, 2017 08:31
-
-
Save dlsniper/4482aebf53330fba6b76c8216077cbf6 to your computer and use it in GitHub Desktop.
Go limited worker count
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" | |
"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