douba7784 2018-08-11 23:49
浏览 31
已采纳

golang频道是否基于LIFO? [重复]

This question already has an answer here:

I was wondering regarding the order of elements in golang channels. After running a few examples, it seems that the order in which the elements come off the channel is "last in first out". Am I right?

The following snippet is the example which I used. After running the code, the output is 20 10, while 10 was sent to the channel first and 20 last.

package main

import "fmt"

func multiply(c chan int, num int) {
    c <- num * 10
}

func main() {
    c := make(chan int)

    go multiply(c, 1)
    go multiply(c, 2)

    v1 := <-c
    v2 := <-c
    fmt.Println(v1, v2)
}
</div>
  • 写回答

1条回答 默认 最新

  • doutong7216 2018-08-12 00:01
    关注

    Golang channels are not LIFO.

    Channels act as first-in-first-out queues. For example, if one goroutine sends values on a channel and a second goroutine receives them, the values are received in the order sent.

    Values sent on the channel will be received whenever the receiver of the channel is ready. And if not then it will block. For managing that you can go for buffered channels.

    Below code will check if the values are available to be received from the channel.

    package main
    
    import "fmt"
    
    func multiply(c chan int, num int) {
        c <- num * 10
    }
    
    func main() {
        c := make(chan int, 3)
    
        go multiply(c, 1)
        go multiply(c, 2)
        go multiply(c, 3)
    
        for i:=0;i<3;i++{
             foo, ok := <- c
             if !ok {
                    fmt.Println("done")
                    return
             }
             fmt.Println(foo)
        }
    
    }
    

    Working code on Go playground

    Buffered Channels

    Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:

    make(chan int, 100)
    

    The capacity, in number of elements, sets the size of the buffer in the channel. If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready. Otherwise, the channel is buffered and communication succeeds without blocking if the buffer is not full (sends) or not empty (receives). A nil channel is never ready for communication.

    In your case, it depends on which go routine will send the value on the channel first. The values that you are printing completely depends on the go routines.

    For more information go through Golang Channels

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部