package main import ( "fmt" "time" ) // 工作函数:通过 channel 接收退出信号 func worker(quit <-chan struct{}) { defer fmt.Println("worker:清理资源完成") // 确保退出前执行清理 for { select { case <-quit: fmt.Println("worker:收到退出信号,准备退出") return // 退出 Goroutine default: fmt.Println("worker:正在处理任务...") time.Sleep(500 * time.Millisecond) } } } func main() { quit := make(chan struct{}) // 退出信号通道(struct{} 零内存开销) // 启动工作 Goroutine go worker(quit) // 主程序运行 2 秒后触发退出 time.Sleep(2 * time.Second) close(quit) // 关闭通道(广播退出信号) // 等待 worker 完成清理 time.Sleep(1 * time.Second) fmt.Println("主程序退出") }