On Wed, 13 Apr 2022 01:40:22 -0700 (PDT) Zhaoxun Yan <yan.zhao...@gmail.com> wrote:
> Since I found if inserting into a buffered channel could cause a > crash if it is full already > ( now I only use unbuffered channels in work) > https://groups.google.com/g/golang-nuts/c/U8lz6noKkuA > > package main > > var c = make(chan int, 1) > > func main() { > > c <- 1 > c <- 2 //fatal error: all goroutines are asleep - deadlock! > c <- 3 > > } > > I made up a work around that just dumps the new message if the buffer > is full: > > package main > > import ( > "fmt" > "sync" > ) > > type ChanInt struct{ > Ch chan int > Mu *sync.Mutex > } > > var c = ChanInt{make(chan int, 1), new(sync.Mutex)} > > func (ch ChanInt) Fill(k int){ > ch.Mu.Lock() > defer ch.Mu.Unlock() > > if len(ch.Ch) < cap(ch.Ch){ > ch.Ch <- k > } > } > I believe the idiom way is to use select to check if channel is full or not. See "leaky buffer" section on https://go.dev/doc/effective_go#channels . -- { "github":"github.com/shuLhan", "site":"kilabit.info" } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/20220413164344.4de8abf1%40inspiro.localdomain.
pgprGXLN9egXW.pgp
Description: OpenPGP digital signature