Sobes.tech
Senior

What to tell the interviewer (if asked) "I would use a worker pool with a fixed number of workers, a task channel, and sync.WaitGroup. The workers will perform the requests, and timeout and cancellation will be controlled via the context. I will gather the results in a buffer protected by a mutex (or through a separate channel)." Now it's your turn Write the code in this chat. I will check it and give feedback. If you don't know where to start, ask for a hint. Good luck!

sobes.tech AI

Vastus AI-lt

go package main

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

// Task esindab ülesannet töötluseks type Task struct { id int // muud väljad }

// WorkerPool rakendab töögrupi 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 } // Ülesande töötlemine res := processTask(task) select { case results <- res: case <-ctx.Done(): return } } } }

func processTask(t Task) string { // töö simulatsioon time.Sleep(100 * time.Millisecond) return fmt.Sprintf("tulemus ülesande %d jaoks", 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)
}

// Eraldi goroutine tulemuste kanali sulgemiseks pärast töötajate lõpetamist
go func() {
	wg.Wait()
	close(results)
}()

// Ülesannete saatmine
go func() {
	for i := 0; i < 20; i++ {
		tasks <- Task{id: i}
	}
	close(tasks)
}()

// Tulemuste kogumine
for res := range results {
	fmt.Println(res)

} }