Este é um pool de threads de trabalho idiomático no Go?
Estou tentando escrever um simples pool de trabalhadores com goroutines.
O código que escrevi é idiomático? Se não, então o que deve mudar?Quero poder definir o número máximo de threads de trabalho como 5 e bloquear até que um trabalhador fique disponível se todos os 5 estiverem ocupados. Como estender isso para ter apenas um pool de 5 trabalhadores no máximo? Devo gerar as 5 goroutines estáticas e dar a cada umawork_channel
?código:
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func worker(id string, work string, o chan string, wg *sync.WaitGroup) {
defer wg.Done()
sleepMs := rand.Intn(1000)
fmt.Printf("worker '%s' received: '%s', sleep %dms\n", id, work, sleepMs)
time.Sleep(time.Duration(sleepMs) * time.Millisecond)
o <- work + fmt.Sprintf("-%dms", sleepMs)
}
func main() {
var work_channel = make(chan string)
var results_channel = make(chan string)
// create goroutine per item in work_channel
go func() {
var c = 0
var wg sync.WaitGroup
for work := range work_channel {
wg.Add(1)
go worker(fmt.Sprintf("%d", c), work, results_channel, &wg)
c++
}
wg.Wait()
fmt.Println("closing results channel")
close(results_channel)
}()
// add work to the work_channel
go func() {
for c := 'a'; c < 'z'; c++ {
work_channel <- fmt.Sprintf("%c", c)
}
close(work_channel)
fmt.Println("sent work to work_channel")
}()
for x := range results_channel {
fmt.Printf("result: %s\n", x)
}
}