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.

Reply via email to