That is not a general idiom. That is a specialized case that maps the buffer 
size on a channel to the size of an ancillary structure.

In general if you are spinning waiting for channels you’ve done something 
wrong. Go has no concept of cpu affinity so the practice has little value. 

(Note that the leaky buffer example does not spin / busy wait)

> On Apr 13, 2022, at 4:44 AM, Robert Engels <reng...@ix.netcom.com> wrote:
> 
> 
> Adding to a full buffered channel will not cause a crash. It can deadlock 
> just as the unbuffered can - but the deadlocks can be harder to diagnose. 
> 
>>> On Apr 13, 2022, at 3:40 AM, 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
>>     }
>> }
>> 
>> func main() {
>>     
>>     fmt.Println("Channel Status: ",len(c.Ch), cap(c.Ch))
>>     c.Fill(5)
>>     fmt.Println("Channel Status: ", len(c.Ch), cap(c.Ch))
>>     fmt.Println("get one out of Channel:", <-c.Ch)
>>     fmt.Println("Channel Status: ", len(c.Ch), cap(c.Ch))
>>     
>>     c.Fill(6)
>>     // c.Ch <- 7 //fatal error: all goroutines are asleep - deadlock!
>>     c.Fill(7)
>>     fmt.Println("Channel Status: ", len(c.Ch), cap(c.Ch))
>>     fmt.Println("get one out of Channel:", <-c.Ch)
>> }
>> -- 
>> 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/9ca5c13b-7797-4d64-bc2c-1f1ff7281168n%40googlegroups.com.

-- 
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/5A78E74F-6B4F-4577-9EA1-53D8817FACF9%40ix.netcom.com.

Reply via email to