Sobes.tech
Senior

Nima aytish kerak intervyu beruvchiga (agar so'rasa) "Men worker pool bilan ishlardim, unda ishchilar soni belgilangan, vazifalar uchun kanal va sync.WaitGroup bo'ladi. Ishchilar so'rovlarni bajaradi, va timeout hamda bekor qilish kontekst orqali boshqariladi. Natijalarni, mutex bilan himoyalangan bufferga yig'aman (yoki alohida kanal orqali)." Endi sening navating Bu chatda kod yoz. Men tekshiraman va fikr-mulohaza beraman. Qayerdan boshlashni bilmasang, maslahat so'rang. Omad!

sobes.tech AI

AIdan javob

go package main

import ( "context" "fmt" "sync" "time" )

// Task, bir işleme görevi temsil eder type Task struct { id int // diğer alanlar }

// WorkerPool, işçilerin havuzunu uygular 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 } // Görevi işle res := processTask(task) select { case results <- res: case <-ctx.Done(): return } } } }

func processTask(t Task) string { // çalışma simülasyonu time.Sleep(100 * time.Millisecond) return fmt.Sprintf("sonuç for task %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)
}

// Ayrı bir goroutine, işçiler tamamlandıktan sonra sonuç kanalını kapatır
go func() {
	wg.Wait()
	close(results)
}()

// Görevleri gönder
go func() {
	for i := 0; i < 20; i++ {
		tasks <- Task{id: i}
	}
	close(tasks)
}()

// Sonuçları topla
for res := range results {
	fmt.Println(res)
}

}