Cosa dire all'intervistatore (se chiedono) "Userei un pool di worker con un numero fisso di worker, un canale per i compiti e sync.WaitGroup. I worker eseguiranno le richieste, e timeout e cancellazione saranno controllati tramite il contesto. Raccoglierò i risultati in un buffer, protetto da un mutex (o tramite un canale separato)." Ora tocca a te Scrivi il codice in questa chat. Lo controllerò e ti darò feedback. Se non sai da dove cominciare, chiedi un suggerimento. Buona fortuna!
sobes.tech AI
Risposta dell'AI
go package main
import ( "context" "fmt" "sync" "time" )
// Task rappresenta un compito da elaborare type Task struct { id int // altri campi }
// WorkerPool implementa un pool di lavoratori func WorkerPool(ctx context.Context, tasks <-chan Task, results chan<- string, wg *sync.WaitGroup) { defer wg.Done() for { select { case <-ctx.Done(): return case task, ok := <-tasks: if !ok { return } // Elaborazione del compito res := processTask(task) select { case results <- res: case <-ctx.Done(): return } } } }
func processTask(t Task) string { // simulazione di lavoro time.Sleep(100 * time.Millisecond) return fmt.Sprintf("risultato per il compito %d", t.id) }
func main() { tasks := make(chan Task) results := make(chan string) var wg sync.WaitGroup
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
workerCount := 5
wg.Add(workerCount)
for i := 0; i < workerCount; i++ {
go WorkerPool(ctx, tasks, results, &wg)
}
// Goroutine separato per chiudere il canale dei risultati dopo che i worker hanno finito
go func() {
wg.Wait()
close(results)
}()
// Inviare compiti
go func() {
for i := 0; i < 20; i++ {
tasks <- Task{id: i}
}
close(tasks)
}()
// Raccogliere risultati
for res := range results {
fmt.Println(res)
}
}