İşə götürənə nə demək olar (əgər soruşsalar) "Müəyyən sayda işçi ilə işçi hovuzu istifadə edərdim, tapşırıqlar üçün kanal və sync.WaitGroup. İşçilər sorğuları yerinə yetirəcək və vaxt aşımı və ləğv etmə kontekst vasitəsilə idarə olunacaq. Nəticələri mutex ilə qorunan tamponda toplayacağam (və ya ayrıca kanal vasitəsilə)." İndi sənin növbəndir Bu söhbətdə kodu yaz. Mən yoxlayıb geribildirim verəcəyəm. Haradan başlamağı bilmirsinizsə, ipucu istəyin. Uğurlar!
sobes.tech Süni İntellekt
AI-dan cavab
go package main
import ( "context" "fmt" "sync" "time" )
// Task, işlənmək üçün bir vəzifəni təmsil edir type Task struct { id int // digər sahələr }
// WorkerPool, işçilərin hovuzunu həyata keçirir 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 } // Vəzifənin işlənməsi res := processTask(task) select { case results <- res: case <-ctx.Done(): return } } } }
func processTask(t Task) string { // işin simulasyonu time.Sleep(100 * time.Millisecond) return fmt.Sprintf("nəticə üçün vəzifə %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)
}
// İşçilər tamamlandıqdan sonra nəticə kanalını bağlamaq üçün ayrıca goroutine
go func() {
wg.Wait()
close(results)
}()
// Vəzifələri göndəririk
go func() {
for i := 0; i < 20; i++ {
tasks <- Task{id: i}
}
close(tasks)
}()
// Nəticələri toplayırıq
for res := range results {
fmt.Println(res)
}
}