blog icon indicating copy to clipboard operation
blog copied to clipboard

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

Open geektutu opened this issue 5 years ago • 7 comments

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

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

geektutu avatar Dec 16 '20 01:12 geektutu

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

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

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

DasyDong avatar Dec 31 '20 07:12 DasyDong

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

geektutu avatar Dec 31 '20 14:12 geektutu

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

fufay avatar Jul 23 '21 06:07 fufay

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

GodXuebi avatar Jul 29 '21 07:07 GodXuebi

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

正解

youngsailor avatar Sep 08 '21 05:09 youngsailor

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

正确的

ShiMaRing avatar Jul 16 '22 13:07 ShiMaRing