dougu3988 2015-08-19 15: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 15: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条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图