package main

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

const (
	jobCount    = 10
	workerCount = 3
	bufferSize  = 5 // 缓冲通道
)

func main() {
	jobs := make(chan int, bufferSize)
	var wg sync.WaitGroup

	// 1. 启动 worker（fan-out）
	for w := 1; w <= workerCount; w++ {
		wg.Add(1)
		go worker(w, jobs, &wg)
	}

	// 2. 发送任务（主 goroutine）
	for j := 1; j <= jobCount; j++ {
		jobs <- j
	}
	close(jobs) // 关键：关闭通道，让 range 自然结束

	// 3. 等待所有 worker 处理完
	wg.Wait()
	fmt.Println("all jobs done")
}

func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	// range 会在通道关闭且读完剩余数据后自动退出
	for j := range jobs {
		fmt.Printf("worker-%d processing job-%d\n", id, j)
		time.Sleep(300 * time.Millisecond) // 模拟耗时
	}
	fmt.Printf("worker-%d shutdown\n", id)
}
