
Go 函数:管理 goroutine 生命周期
在 Go 中,goroutine 是并发执行的轻量级线程。管理它们的 生命周期至关重要,以避免内存泄漏和死锁等问题。
Goroutine 生命周期
goroutine 生命周期包括以下阶段:
-
创建:使用
go关键字创建。 - 执行:goroutine 开始执行其代码。
- 终止:goroutine 执行完成或退出。
- 清理:goroutine 的资源被释放。
管理 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 取消 Goroutine
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
}使用 Channel 阻塞 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 的执行并防止资源泄漏。










