package main

import (
	"fmt"
	"time"
)

// section: problem
func processWithWorkers(items []string, workers int) {
	ch := make(chan string)

	for i := 0; i < workers; i++ {
		go func(id int) {
			for item := range ch { // Blocks forever - ch never closed!
				fmt.Printf("Worker %d processing: %s\n", id, item)
				time.Sleep(50 * time.Millisecond)
			}
			fmt.Printf("Worker %d exiting\n", id) // NEVER PRINTED
		}(i)
	}

	for _, item := range items {
		ch <- item
	}
	// Returns without closing ch - workers stuck in range forever!
}

// section: problem

func main() {
	items := []string{"a", "b", "c", "d", "e"}
	processWithWorkers(items, 3)

	fmt.Println("Function returned - but workers are still blocked!")
	time.Sleep(500 * time.Millisecond)
	fmt.Println("Program ending - 3 leaked goroutines still waiting")
}
