Junior — Middle
Kuidas saab kontrollida rakenduses aktiivsete voogude arvu?
sobes.tech AI
Vastus AI-lt
In Go, to control the number of active threads (goroutines), mechanisms of synchronization and parallelism limitation are commonly used:
-
Buffered channels as semaphores: create a channel with limited capacity and send a value into it before starting a goroutine, and receive a value after it finishes, thus limiting the number of goroutines running simultaneously.
-
sync.WaitGrouppackage: helps to wait for a group of goroutines to finish, but does not limit their number. -
golang.org/x/sync/semaphorepackage: provides a convenient semaphore for limiting parallelism.
Example using a semaphore channel:
sem := make(chan struct{}, 5) // maximum 5 goroutines at the same time
for _, task := range tasks {
sem <- struct{}{} // blocks if already 5 goroutines are running
go func(t Task) {
defer func() { <-sem }() // releases a slot
process(t)
}(task)
}
// Wait for all goroutines to finish
for i := 0; i < cap(sem); i++ {
sem <- struct{}{}
}
This way, you can control the number of active threads and avoid excessive resource consumption.