Go 函数:管理 goroutine 生命周期
在 Go 中,goroutine 是并发执行的轻量级线程。管理它们的 生命周期至关重要,以避免内存泄漏和死锁等问题。
goroutine 生命周期包括以下阶段:
可以通过使用 sync.WaitGroup 来等待 goroutine 终止。
立即学习“go语言免费学习笔记(深入)”;
import ( "sync" "fmt" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) // 递增等待组计数 go func(i int) { defer wg.Done() // 递减等待组计数 fmt.Println(i) }(i) } wg.Wait() // 阻塞主 goroutine,直到等待组计数为 0 }
context.Context 允许取消 goroutine。
import ( "context" "fmt" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // 取消上下文 go func() { for { select { case <-ctx.Done(): fmt.Println("Goroutine canceled") return default: fmt.Println("Goroutine running") } } }() time.Sleep(time.Second * 5) cancel() // 取消上下文并终止 goroutine }
通道可以用来阻塞 goroutine,直到收到消息。
import ( "fmt" "sync" ) func main() { var done = make(chan struct{}) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for { select { case <-done: fmt.Println("Goroutine terminated") return default: fmt.Println("Goroutine running") } } }() time.Sleep(time.Second * 5) close(done) // 关闭通道并终止 goroutine wg.Wait() }
在处理外部请求或长时间运行的任务时,管理 goroutine 生命周期至关重要。通过使用上述技术,你可以控制 goroutine 的执行并防止资源泄漏。
以上就是Golang 函数:如何管理 goroutine 的生命周期?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号