求解关于TheWayToGo中描述协程未完成写入通道时,如果主程序结束,该协程不会被垃圾回收的章节

Groza · 2019-04-24 08:39:48 · 2713 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2019-04-24 08:39:48 的主题,其中的信息可能已经有所发展或是发生改变。

"The Way to Go" ---- page 395

The code which calls this method can then iterate over the container like:

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),不要这样写)

对这一段的疑问我都在上面的括号里写出来了,还望解惑,谢谢各位大佬!


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2713 次点击  
加入收藏 微博
2 回复  |  直到 2019-04-24 15:21:07
hei6775
hei6775 · #1 · 6年之前

没看过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 @Groza

Groza
Groza · #2 · 6年之前

1楼 @hei6775 非常感谢,我刚好也去找了一些文章看了,差不多弄明白作者这段原文的意思了,您的回复再次确认了我心中的想法是正确的,并且补充了更多的细节。再次感谢您认真写下的回复。 我正在拜读这一篇博文。 @hei6775

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传