// Concurrency: goroutines, channels, and select
package main

import (
	"fmt"
	"time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		time.Sleep(10 * time.Millisecond)
		results <- j * j
	}
}

func main() {
	jobs := make(chan int, 5)
	results := make(chan int, 5)

	for w := 1; w <= 3; w++ {
		go worker(w, jobs, results)
	}

	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)

	timeout := time.After(500 * time.Millisecond)
	for i := 0; i < 5; i++ {
		select {
		case r := <-results:
			fmt.Println("result:", r)
		case <-timeout:
			fmt.Println("timed out")
			return
		}
	}
}
