Go Chan有缓冲无缓冲区别

go chan有缓冲无缓冲区别

同步非同步区别

  • 有缓冲与无缓冲
    1
    2
    3
    c1:=make(chan int)        //无缓冲
    c2:=make(chan int,1) //有缓冲
    c1 <- 1
  • 无缓冲c1 通道放入1后需要有携程一直处理,不然一直会阻塞下去
  • 方向论证代码(错误示例)
    1
    2
    3
    4
    5
    6
    7
    package main

    func main() {
    c1 := make(chan int)
    c1 <- 1 //没有处理接收就堵塞这里了 //fatal error: all goroutines are asleep - deadlock!
    <-c1
    }
  • 正确示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    package main

    import (
    "fmt"
    "time"
    )

    func read(out chan int) {
    for {
    fmt.Println("waiting => ", time.Now())
    fmt.Println("read => ", <-out)
    }
    }

    func main() {
    out := make(chan int)
    go read(out)

    for i := 1; i <= 5; i++ {
    time.Sleep(time.Second)
    fmt.Println("set => ", i, time.Now())
    out <- i
    }

    }
  • 有缓冲示例
    1
    2
    3
       c2 := make(chan int,2)
    c2 <- 1 //这里不会阻塞 因为缓冲大小是2 只有当满了2个值后还无取出 则会阻塞
    fmt.Println(<-c2) // 1