goroutine 与 channel
func worker(id int, jobs <-chan int, results chan<- int){
for j := range jobs { results <- j * 2 }
}
func main(){
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 3; w++ { go worker(w, jobs, results) }
for j := 1; j <= 5; j++ { jobs <- j }
close(jobs)
for a := 1; a <= 5; a++ { fmt.Println(<-results) }
}并发模式
- 扇入/扇出(fan-in/fan-out)
- 工作池(worker pool)
- 上下文与超时控制
建议
限制 goroutine 数量、避免共享可变状态、用 context 管理生命周期。