Junior — Middle
How to determine the limit on the number of goroutines running simultaneously in Go?
sobes.tech AI
Answer from AI
The Go language does not have a built-in mechanism for directly limiting the number of goroutines running simultaneously. However, to control the level of parallelism, semaphores or channels with limited capacity are usually used.
Example of limiting the number of goroutines running simultaneously using a channel:
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, sem chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
sem <- struct{}{} // acquire a slot
fmt.Printf("Goroutine %d started work\n", id)
time.Sleep(time.Second) // simulate work
fmt.Printf("Goroutine %d finished work\n", id)
<-sem // release the slot
}
func main() {
const maxGoroutines = 3
sem := make(chan struct{}, maxGoroutines) // buffered channel limits goroutines
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1)
go worker(i, sem, &wg)
}
wg.Wait()
}
In this example, the sem channel with a buffer of maxGoroutines limits the number of goroutines executing simultaneously. Each goroutine places an empty struct into the channel before starting work, occupying a slot, and releases it after finishing. Thus, no more than maxGoroutines goroutines will work at the same time.