geektutu / blog

极客兔兔的博客,Coding Coding 创建有趣的开源项目。
https://geektutu.com
Apache License 2.0
166 stars 21 forks source link

如何退出协程 goroutine (其他场景) | Go 语言高性能编程 | 极客兔兔 #115

Open geektutu opened 3 years ago

geektutu commented 3 years ago

https://geektutu.com/post/hpg-exit-goroutine.html

Go 语言/golang 高性能编程,Go 语言进阶教程,Go 语言高性能编程(high performance go)。本文介绍了协程没有正常关闭导致内存泄漏的场景,并介绍了如何借助通道/信道(channel) 优雅地退出协程。

DasyDong commented 3 years ago

ch := make(chan int) // 带缓冲区

ch := make(chan int, 10) // 不带缓冲区,缓冲区满之前,即使没有接收方,发送方不阻塞

第一个才是不带缓冲区吧? 第二个是带缓冲区

geektutu commented 3 years ago

@DasyDong fixed, thanks. hpg-exit-goroutine.md

fufay commented 2 years ago

如果不关闭chan而要使用for加select结构,加个default:return亦可。 如果关闭chan,则goroutine中使用for range亦可。

GodXuebi commented 2 years ago

v, beforeClosed := <-ch 你后面的解释不明白,beforeClosed返回false是当且仅当ch关闭了,而且chan为空。如果ch关闭了,chan里面还有没有接受的元素,beforeClosed返回的依然是true。

youngsailor commented 2 years ago

@GodXuebi v, beforeClosed := <-ch 你后面的解释不明白,beforeClosed返回false是当且仅当ch关闭了,而且chan为空。如果ch关闭了,chan里面还有没有接受的元素,beforeClosed返回的依然是true。

正解

ShiMaRing commented 1 year ago

@GodXuebi v, beforeClosed := <-ch 你后面的解释不明白,beforeClosed返回false是当且仅当ch关闭了,而且chan为空。如果ch关闭了,chan里面还有没有接受的元素,beforeClosed返回的依然是true。

正确的