Created
January 6, 2019 12:13
-
-
Save dkarbayev/f94e60b71095bc5845e6453170a157fd to your computer and use it in GitHub Desktop.
Limit the number of concurrently running goroutines
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" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
var wg = sync.WaitGroup{} | |
maxGoroutines := 4 | |
guard := make(chan struct{}, maxGoroutines) | |
for i := 0; i < 15; i++ { | |
guard <- struct{}{} | |
wg.Add(1) | |
go func(n int) { | |
worker(n) | |
<-guard | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
fmt.Println("done") | |
} | |
func worker(i int) { | |
s := time.Duration(int64(rand.Intn(3) + 2) * int64(time.Second)) | |
fmt.Printf("doing work on %d, sleep %v\n", i, s) | |
time.Sleep(s) | |
fmt.Println("done sleeping", i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment