"The Way to Go" ---- page 395
>
The code which calls this method can then iterate over the container like:
```go
for x := range container.Iter() { ... }
```
which can run in its own goroutine, so then the above iterator employs a channel and two goroutines (which may run in separate threads). Then we have a typical producer-consumer pattern. If the program terminates before the goroutine is done writing values to the channel, then that goroutine will not be garbage collected; this is by design(这是指Golang的design还是上面那段代码的design?). This seems like wrong behavior, but channels are for threadsafe communication(不太明白这种行为和和线程安全有什么关系). In that context, a goroutine hung trying to write to a channel that nobody will ever read from is probably a bug and not something you’d like to be silently garbage-collected.(因为上面那个design到底指的谁我不太明白,所以这个地方到底是想表达“这看起来像bug(如果之前指的是golang的design)”,还是像表达“这样就是一个bug”(如果指之前的代码的design),不要这样写)
对这一段的疑问我都在上面的括号里写出来了,还望解惑,谢谢各位大佬!
1楼 <a href="/user/hei6775" title="@hei6775">@hei6775</a> 非常感谢,我刚好也去找了一些文章看了,差不多弄明白作者这段原文的意思了,您的回复再次确认了我心中的想法是正确的,并且补充了更多的细节。再次感谢您认真写下的回复。 我正在拜读这一篇博文。
<a href="/user/hei6775" title="@hei6775">@hei6775</a>
#2
更多评论
没看过The Way To Go,从提问的代码来看。
container.Iter()应该是通道,像这样
```
yourChannel := make(chan int)
for x := range yourChannel{
//.............
}
```
因为申明的是无缓冲通道,所以一个`goroutine`在往通道里存数据,一个`goroutine`在从通道中取数据,在那个存数据的goroutine意外提前结束时那么取数据的`goroutine`将会堵塞,造成`goroutine`泄漏,这个`goroutine`将不会被GC。
design应该是指 文章强调说明golang中的通道就是如此设计的。
这样的设计是为了线程安全,简单来说就是为了同步操作,避免竞争
关于通道更多的可以看`https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html`
<a href="/user/Groza" title="@Groza">@Groza</a>
#1