Junior — Middle
Is it possible to set a limit on the number of concurrently running threads in the Go language?
sobes.tech AI
Answer from AI
In Go, there is no built-in mechanism to directly limit the number of goroutines running simultaneously. Goroutines can be very numerous and lightweight. To limit the number of concurrently executing goroutines, semaphores or channels with limited capacity are usually used.
Example of limiting the number of goroutines 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("Worker %d started\n", id)
time.Sleep(time.Second) // work
fmt.Printf("Worker %d finished\n", id)
<-sem // release the slot
}
func main() {
const maxConcurrent = 3
sem := make(chan struct{}, maxConcurrent) // limit channel
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1)
go worker(i, sem, &wg)
}
wg.Wait()
}
Here, the channel sem with buffer maxConcurrent limits the number of goroutines running simultaneously to 3.