dougu3988 2015-08-19 07:06 采纳率: 100%
浏览 40
已采纳

去渠道:为什么有两个不同的输出?

I'm trying to understand channels in Go. Here is a code example:

package main

import "fmt"

func main() {
    m := make(map[int]string)
    m[2] = "First Value"
    c := make(chan bool)
    go func() {
        m[2] = "Second Value"
        c <- true
    }()
    fmt.Printf("1-%s
", m[2])
    fmt.Printf("2-%s
", m[2])
    _ = <-c
    fmt.Printf("3-%s
", m[2])
    fmt.Printf("4-%s
", m[2])
}

Sometimes the output of the above code was (result 1):

1-First Value
2-First Value
3-Second Value
4-Second Value

but sometimes I got (result 2):

1-First Value
2-Second Value
3-Second Value
4-Second Value

After changing c := make(chan bool) to c := make(chan bool, 1), the same occurred: sometimes result 1, sometimes result 2.

Why?

展开全部

  • 写回答

2条回答 默认 最新

  • duanguan1573 2015-08-19 07:23
    关注

    Your results makes perfect sense. As go routine run independent of each other, you would never know when go routine will start executing. As soon as line

    m[2] = "Second Value"
    

    is executed it will be reflected on your main go routine.

    Hence when above line is executed between first and second print of your program you see result as

    1-First Value
    2-Second Value
    3-Second Value
    4-Second Value
    

    When it is not you see other one. Before third print you ensure that other go routine is finished.

    Just to clear it even more if you modify your program a little bit like

    package main
    
    import "fmt"
    import "time"
    
    func main() {
        m := make(map[int]string)
        m[2] = "First Value"
        c := make(chan bool)
        go func() {
            m[2] = "Second Value"
            c <- true
        }()
        time.Sleep(time.Second)
        fmt.Printf("1-%s
    ", m[2])
        fmt.Printf("2-%s
    ", m[2])
        _ = <-c
        fmt.Printf("3-%s
    ", m[2])
        fmt.Printf("4-%s
    ", m[2])
    }
    

    <kbd>Playground</kbd>

    You will most probably get the following output

    1-Second Value
    2-Second Value
    3-Second Value
    4-Second Value
    

    Hope it helps.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部