Go channels and deadlock

后端 未结 3 815
情歌与酒
情歌与酒 2020-12-24 14:23

I\'m trying to understand the Go language. I tried to create two goroutines that chain the flow between them using two channels:

func main() {
c1 := make(cha         


        
3条回答
  •  轮回少年
    2020-12-24 15:05

    to prevent the channel from overflowing, you can ask for the channel's current capacity and dry it before writing again.

    in my case, the game takes place at 60fps and the mouse moves much faster, so it is always good to check that the channel has been cleared before writing again.

    notice that the previous data is lost

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        // you must specify the size of the channel, 
        // even for just one element, or the code doesn't work
        ch := make( chan int, 1 )
        fmt.Printf("len: %v\n", len(ch))
        fmt.Printf("cap: %v\n\n", cap(ch))
    
        ch <- 1
    
        for i := 0; i != 100; i += 1 {
            fmt.Printf("len: %v\n", len(ch))
            fmt.Printf("cap: %v\n\n", cap(ch))
    
            if cap( ch ) == 1 {
                <- ch
            }
    
            ch <- i
    
            fmt.Printf("len: %v\n", len(ch))
            fmt.Printf("cap: %v\n\n", cap(ch))
        }
        fmt.Printf("end!\n")
    }
    

提交回复
热议问题