Skip to content

Instantly share code, notes, and snippets.

@vadikgo
Created August 30, 2020 12:08
Show Gist options
  • Save vadikgo/4e1797282e9ee3a5c576c6633f1c3ee4 to your computer and use it in GitHub Desktop.
Save vadikgo/4e1797282e9ee3a5c576c6633f1c3ee4 to your computer and use it in GitHub Desktop.
test go routines parallel run
package main
import (
"fmt"
"sync"
"time"
)
func makeRange(min, max int) []int {
a := make([]int, max-min+1)
for i := range a {
a[i] = min + i
}
return a
}
// https://codereview.stackexchange.com/questions/171311/limiting-the-maximum-amount-of-goroutines-run-simultaneously
func main() {
inp := makeRange(10, 90)
var wg sync.WaitGroup
// Create bufferized channel with size 5
goroutines := make(chan struct{}, 5)
// Read data from input channel
for i, data := range inp {
// 1 struct{}{} - 1 goroutine
goroutines <- struct{}{}
wg.Add(1)
//fmt.Println(data)
go func(index int, pdata int, goroutines <-chan struct{}, wg *sync.WaitGroup) {
// Process data
time.Sleep(1 * time.Millisecond)
fmt.Println(index, pdata, len(goroutines))
// Read from "goroutines" channel to free space for new goroutine
<-goroutines
wg.Done()
}(i, data, goroutines, &wg)
}
wg.Wait()
close(goroutines)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment