美文网首页
channel详解

channel详解

作者: 只争朝夕々 | 来源:发表于2020-07-05 14:44 被阅读0次

    无缓冲通道

    只有当读写都准备好时才不会被阻塞

    func main() {
        ch := make(chan struct{})
    
        go func() {
            <-ch
        }()
    
        ch <- struct{}{}
    
        fmt.Println("done")
    }
    

    输出:

    done
    
    Process finished with exit code 0
    

    有缓冲通道

    • 当有缓冲通道长度未满时,写入是无阻塞的
    func main() {
        ch := make(chan struct{}, 2)
        ch <- struct{}{}
        fmt.Println("done")
    }
    

    输出:

    done
    
    Process finished with exit code 0
    
    • 当有缓冲通道长度已满时,写入是阻塞的
    func main() {
        ch := make(chan struct{}, 2)
    
        go func() {
            ch <- struct{}{}
            fmt.Println("append ch")
        }()
    
        for i := 0; i < 2; i++ {
            ch <- struct{}{}
        }
    
        time.Sleep(time.Second)
        fmt.Println("done")
    }
    

    输出:

    done
    
    Process finished with exit code 0
    

    相关文章

      网友评论

          本文标题:channel详解

          本文链接:https://www.haomeiwen.com/subject/esqvqktx.html