golang函数与goroutine的资源分配
作者:QuietDream
时间:2024-05-09
浏览:0
函数在执行时分配资源,执行完毕后自动释放;而goroutine在创建时分配资源,需显式关闭或使用context、WaitGroup确保释放,防止内存泄漏和性能下降。
函数在执行时分配资源,执行完毕后自动释放;而 goroutine 在创建时分配资源,需显式关闭或使用 context、WaitGroup 确保释放,防止内存泄漏和性能下降。

Golang 函数与 Goroutine 的资源分配实战
简介
在 Go 语言中,函数和 goroutine 是常被使用的并发性机制。函数是执行代码的单元,而 goroutine 则是并发执行的函数。合理分配函数和 goroutine 的资源至关重要,以优化程序性能和防止资源浪费。
函数的资源分配
函数只在执行时占用资源,在执行完毕后自动释放所有资源。可以通过使用 defer 语句来确保资源在函数返回前释放。例如:
func cleanup() {
// 释放资源
}
func main() {
defer cleanup()
// 执行代码
}Goroutine 的资源分配
与函数不同,goroutine 在创建时分配资源,并且直到 goroutine 退出才释放这些资源。如果不及时释放 goroutine,会导致内存泄漏和性能下降。
有几种方法可以确保 goroutine 释放资源:
显式关闭 channel 和 other 资源:
c := make(chan int) // 使用 channel close(c)
使用
context.Done():ctx, cancel := context.WithCancel(context.Background()) // 使用 context cancel()
通过
WaitGroup等待 goroutine 退出:var wg sync.WaitGroup wg.Add(1) go func() { // 执行代码 wg.Done() }() wg.Wait()
实战案例
在以下示例中,我们创建了多个 goroutine 来执行异步任务:
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fmt.Println("Goroutine", i)
// 使用 ctx 来响应取消请求
select {
case <-ctx.Done():
fmt.Println("Goroutine", i, "cancelled")
return
default:
// 继续执行任务
}
}(i)
}
// 取消所有 goroutine
cancel()
wg.Wait()
}运行此程序,输出如下:
Goroutine 0 Goroutine 1 Goroutine 2 Goroutine 3 Goroutine 4 Goroutine 5 Goroutine 0 cancelled Goroutine 1 cancelled Goroutine 2 cancelled Goroutine 3 cancelled Goroutine 4 cancelled Goroutine 5 cancelled Goroutine 6 Goroutine 7 Goroutine 8 Goroutine 9 Goroutine 6 cancelled Goroutine 7 cancelled Goroutine 8 cancelled Goroutine 9 cancelled
从输出中可以看出,当 cancel() 函数被调用时,所有 goroutine 都及时释放了资源。
作者最新文章
高通骁龙8至尊版Gen6实物图曝光:侧置DRAM与HPB散热结构解析
2026-09-08 17:07
电影剪辑实战:镜头组织、节奏控制与声音衔接技巧
2026-09-04 09:27
RedmiNote13Pro+桌面动画怎么设置 RedmiNote13Pro+桌面动画设置方法
2026-08-25 14:24
Snap推出新一代SPECS增强现实眼镜 售价2195美元
2026-08-25 10:04
一加 Nord Buds 4 耳机规格公布:52dB 主动降噪、12mm 动圈单元,6 月 25 日海外发布
2026-08-25 09:55
上一篇:
Redis在Java中的应用详解
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































