Junior — Middle
Tell about the most memorable task related to using goroutines.
sobes.tech AI
Answer from AI
One memorable task with goroutines involved parallel processing of a large number of requests to an external API.
It was necessary to send hundreds of requests simultaneously while controlling the number of goroutines running at the same time to avoid overloading the system and receiving API rejections.
Solution:
- Used a goroutine pool with a limit on the number.
- For this, a buffered channel was used as a semaphore to limit the number of active goroutines.
- Each goroutine processed one request and freed a slot upon completion.
Example code:
sem := make(chan struct{}, 10) // maximum 10 goroutines
for _, req := range requests {
sem <- struct{}{} // acquire a slot
go func(r Request) {
defer func() { <-sem }() // release the slot
processRequest(r)
}(req)
}
// wait for all goroutines to finish
for i := 0; i < cap(sem); i++ {
sem <- struct{}{}
}
This allowed efficient resource utilization and prevented overload.