Sobes.tech
Junior — Middle

How can you control the number of active threads in an application?

sobes.tech AI

Answer from AI

In Go, mechanisms for controlling the number of active goroutines typically include synchronization and parallelism limiting techniques:

  • Buffered channels as semaphores: create a channel with limited capacity and send a value before starting a goroutine, then receive after completion, thus limiting the number of concurrently running goroutines.

  • sync.WaitGroup package: helps wait for a group of goroutines to finish but does not limit their number.

  • golang.org/x/sync/semaphore package: 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 5 goroutines are already running
    go func(t Task) {
        defer func() { <-sem }() // release slot
        process(t)
    }(task)
}

// Wait until all goroutines 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.

How can you control the number of active threads in… - sobes.tech