Skip to content

Instantly share code, notes, and snippets.

@dkarbayev
Created January 6, 2019 12:13
Show Gist options
  • Save dkarbayev/f94e60b71095bc5845e6453170a157fd to your computer and use it in GitHub Desktop.
Save dkarbayev/f94e60b71095bc5845e6453170a157fd to your computer and use it in GitHub Desktop.
Limit the number of concurrently running goroutines
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