我有一个goroutine,它调用一个方法,并在一个通道上传递返回值:
ch := make(chan int, 100)
go func(){
for {
ch <- do_stuff()
}
}()
我怎样才能阻止这样的一场闹剧?
我有一个goroutine,它调用一个方法,并在一个通道上传递返回值:
ch := make(chan int, 100)
go func(){
for {
ch <- do_stuff()
}
}()
我怎样才能阻止这样的一场闹剧?
EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...
如果您的goroutine仅用于处理来自chan的项目,您可以使用"关闭"内置和频道的特殊接收表单.
也就是说,一旦你发送完chan上的项目,你就可以关闭它.然后在goroutine中,你会得到一个额外的参数给receive操作符,显示通道是否已关闭.
下面是一个完整的示例(等待组用于确保该过程继续,直到goroutine完成):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
ch := make(chan int)
go func() {
for {
foo, ok := <- ch
if !ok {
println("done")
wg.Done()
return
}
println(foo)
}
}()
ch <- 1
ch <- 2
ch <- 3
close(ch)
wg.Wait()
}