gpt4 book ai didi

Golang 中的协程大小不是线性增加的

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:10 26 4
gpt4 key购买 nike

对于下面的代码:

const LOOPNUM int = 200000

func main() {
z := make(chan int16)
for i := 0; i < LOOPNUM; i++ {
go test(z)
}
}

func test(a chan<- int16) {
a <- -1
}

我用 LOOPNUM = 200k 和 400k 运行代码,内存使用情况如下:

goroutine size comparison

有谁知道我将 goroutines 加倍后内存突然增加的原因(以及减少内存使用的任何解决方案)?

谢谢!

最佳答案

您不是在等待 goroutines 完成,因此它会在更改以执行您告诉它的所有操作之前退出。将其更改为:

const LOOPNUM int = 200000
var wg sync.WaitGroup
func main() {
wg = sync.WaitGroup{}
wg.Add(LOOPNUM)
z := make(chan int16)
for i := 0; i < LOOPNUM; i++ {
go test(z)
}
wg.Wait()
}

func test(a chan<- int16) {
a <- -1
wg.Done()
}

你应该对正在发生的事情有更好的了解。

关于Golang 中的协程大小不是线性增加的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46717054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com