duanmie9682 2019-09-08 17:22 采纳率: 100%
浏览 18

在这个例子中如何理解goroutines的执行?

i am trying to understand go routines and how it works. in the below example i have two go routines each sending some messege via channels.i was expecting the channel ch will send messege first but why is go readword(ch) execute after go timeout(t). if i change the order of the go routines call inside main function then readword(ch) will execute first.i am getting very confused about go routines? any help?

func readword(ch chan string) {

    fmt.Println("Type a word, then hit Enter.")
    var word string
    fmt.Scanf("%s", &word)
    ch <- word
}

func timeout(t chan bool) {
    t <- false
}

func main() {
    ch := make(chan string)
    go readword(ch)

    t := make(chan bool)
    go timeout(t)

    select {
    case word := <-ch:
        fmt.Println("Received", word)
    case <-t:
        fmt.Println("Timeout.")
    }
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-09-08 17:32
    关注

    There is no execution ordering guarantee between goroutines unless they communicate with each other using synchronization mechanisms such as channels. You create two goroutines, then wait until you receive a string from ch, or receive from t. There is no explicit synchronization between the two goroutines, so they can execute in any order in a single thread, or simultaneously on different threads. The select statement will read from the first channel that has something in it.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?