douzhuo3233 2017-08-01 18:06
浏览 30

Goroutine导致for循环中的可互换动作

I'm very new to go and I'm not sure why this code has this output. I understand that sleep will cause the new goroutine to start the other thread for the specified amount of time. I'm trying to sequentially map out the logic and it looks like "world" should always print before "hello".

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(1 * time.Millisecond)
        fmt.Println(s, i)
    }
}

func main() {
    go say("world")
    say("hello")
}

Actual Output:

world 0
hello 0
hello 1
world 1
world 2
hello 2
hello 3
world 3
world 4
hello 4

Expected Output:

world 0
hello 0
world 1
hello 1
world 2
hello 2

...etc

  • 写回答

3条回答 默认 最新

  • dpxbc88022 2017-08-01 18:13
    关注

    I understand that sleep will cause the new goroutine to start the other thread for the specified amount of time

    This is partly incorrect!

    This would be correct on a machine with only one core where only one thread can be executed at a time.

    On a machine with multiple cores go can execute as many goroutines parallel as there are cores. With parallel executed goroutines there is no guarantee at all, what will be executed before or after.

    评论

报告相同问题?

悬赏问题

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