gpt4 book ai didi

go - 如果我知道 golang channel 的所有值是有限的,我是否应该消耗它们?

转载 作者:IT王子 更新时间:2023-10-29 01:33:44 26 4
gpt4 key购买 nike

我正在处理 Concurrency sectionA Tour of Go ,而且我对使用有限 channel 的正确 Go 约定感到好奇。在本练习中,我需要从两个 channel 读取值并确定这些值是否相同且顺序是否相同。如果不是,我可以立即从我的方法中返回 false。但是,如果我这样做,Go 会自动为我清理我的 channel ,还是我的 goroutine 会永远挂起并消耗资源?

处理此问题的最佳方法是将取消 channel 传递到我的 goroutine 中,但由于 goroutine 读取的数据量有限,因此只消耗所有数据似乎没问题。在现实生活中处理这种情况的最佳方法是什么?

最佳答案

Andrew Gerrand's talk at Gopherconslide 37 上涵盖了这个确切的问题.

Create a quit channel and pass it to each walker. By closing quit when the Same exits, any running walkers are terminated.

func Same(t1, t2 *tree.Tree) bool {
quit := make(chan struct{})
defer close(quit)
w1, w2 := Walk(t1, quit), Walk(t2, quit)
for {
v1, ok1 := <-w1
v2, ok2 := <-w2
if v1 != v2 || ok1 != ok2 {
return false
}
if !ok1 {
return true
}
}
}

关于go - 如果我知道 golang channel 的所有值是有限的,我是否应该消耗它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673952/

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