Limit number of goroutines
31 December, 2022
Limit number of goroutines 🚀
Solution 1:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
maxGoroutines := 2
guard := make(chan struct{}, maxGoroutines)
for i := 0; i < 50; i++ {
guard <- struct{}{}
go func(n int) {
worker(n)
<-guard
}(i)
}
}
func worker(i int) {
time.Sleep(time.Second * 10) // processing time for the task
fmt.Println(runtime.NumGoroutine()) // print number or running current goroutines
fmt.Println("doing work on", i)
}
Solution 2:
package main
import (
"fmt"
"time"
)
const LIMIT = 25
func main() {
sem := make(chan int, LIMIT)
for {
sem <- 1 // will block if there is LIMIT ints in sem
go func() {
time.Sleep(time.Second * 10) // processing time for the task
fmt.Println("doing work")
<-sem // removes an int from sem, allowing another to proceed
}()
}
}
Links: