doutan1970 2018-04-22 22:13
浏览 98
已采纳

如何在Golang中与goroutines中的通道安全交互

I am new to go and I am trying to understand the way channels in goroutines work. To my understanding, the keyword range could be used to iterate over a the values of the channel up until the channel is closed or the buffer runs out; hence, a for range c will repeatedly loops until the buffer runs out.

I have the following simple function that adds value to a channel:

func main() {

    c := make(chan int)
    go printchannel(c)
    for i:=0; i<10 ; i++ {
        c <- i
    }

}

I have two implementations of printchannel and I am not sure why the behaviour is different.

Implementation 1:

func printchannel(c chan int) {
    for range c {
        fmt.Println(<-c)
    }
}

output: 1 3 5 7

Implementation 2:

func printchannel(c chan int) {
    for i:=range c {
        fmt.Println(i)
    }
}

output: 0 1 2 3 4 5 6 7 8

And I was expecting neither of those outputs!

Wanted output: 0 1 2 3 4 5 6 7 8 9

Shouldnt the main function and the printchannel function run on two threads in parallel, one adding values to the channel and the other reading the values up until the channel is closed? I might be missing some fundamental go/thread concept here and pointers to that would be helpful.

Feedback on this (and my understanding to channels manipulation in goroutines) is greatly appreciated!

  • 写回答

4条回答 默认 最新

    报告相同问题?

    相关推荐 更多相似问题

    悬赏问题

    • ¥60 有关C#的问题,基础牢固的来
    • ¥15 Python算法设计Seam carving--让图片比例随心缩放
    • ¥15 页面制作,HTML CSS
    • ¥15 通个批处理实现 win7和win10 修改或设置:显示操作系统列表时间为2秒
    • ¥20 报错:Unsupported class file major version 59
    • ¥15 用ASP代码实现跨站脚本攻击
    • ¥50 ABP中怎样接收vue上传的图片
    • ¥15 uniapp设置音频的倍速播放无效
    • ¥15 关于#hc#的问题,如何解决?
    • ¥15 cyclegan跨模态生成