添加元素后通道长度为零

我学习了 Go 中的缓冲通道,但有些魔法对我来说是隐藏的。我有这个代码


package main


import (

    "fmt"

)


func write(ch chan int) {

    for i := 1; i <= 5; i++ {

        ch <- i

        fmt.Printf("Channel's length is %d\n", len(ch))

    }

    close(ch)

}

func main() {

    ch := make(chan int, 2)

    go write(ch)


    for v := range ch {

        fmt.Println(v)

    }

}

输出是


Channel's length is 0

Channel's length is 1

Channel's length is 2

1

2

3

4

Channel's length is 2

Channel's length is 0

5

为什么 write goroutine 中第一次迭代的通道长度为零?我不知道什么?


ibeautiful
浏览 94回答 1
1回答

喵喵时光机

根据 GO 缓冲区的概念,您可以根据定义的缓冲区大小将元素推送到通道中(在您的情况下为 2)。但当一个元素被推入通道时,主 GO 例程正在读取相同的元素,这导致通道大小减小到零。因此,如果您在读取语句之前花一些时间。睡眠,您将得到预期的结果。`package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func write(ch chan int) {&nbsp; &nbsp; for i := 1; i <= 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; ch <- i&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Channel's length is %d\n", len(ch))&nbsp; &nbsp; }&nbsp; &nbsp; close(ch)}func main() {&nbsp; &nbsp; ch := make(chan int, 2)&nbsp; &nbsp; go write(ch)&nbsp; &nbsp; time.Sleep(2*time.Second)&nbsp; &nbsp; for v := range ch {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v)&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(2*time.Second)&nbsp; &nbsp; }}`上述代码的输出是:通道长度为1通道长度为21通道长度为22通道长度为23通道长度为245
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go