drzip28288 2016-05-19 20:26
浏览 36
已采纳

为什么我完全相同的go例程混乱?

I've got the following go code executing routines.

package main

import (
        "fmt"
        "time"
)

func count(id int) {
        for i := 0; i < 10; i++ {
                fmt.Println(id, ":", i)
                time.Sleep(time.Millisecond * 1000)
        }   
}

func main() {
        for i := 0; i < 10; i++ {
                go count(i)
        }   
        time.Sleep(time.Millisecond * 11000)
}

I would expect the output to be:

1 : 0
2 : 0
3 : 0
4 : 0
5 : 0
6 : 0
7 : 0
8 : 0
9 : 0
1 : 1
2 : 1
3 : 1
4 : 1
etc...

but instead, I get:

0 : 0
6 : 0
7 : 0
5 : 0
8 : 0
9 : 0
3 : 0
2 : 0
4 : 0
1 : 0
5 : 1
6 : 1
7 : 1
1 : 1
8 : 1
etc...

Why are they not in order of the original, outside for loop executing the count method? Why are some count methods getting out of sync?

  • 写回答

2条回答 默认 最新

  • dongpao9165 2016-05-19 20:35
    关注

    When a goroutine executes is out of the control of the programmer. You have some control if you use signals via channels and sync.WaitGroup, (like having one goroutine wait until another has finished) but you cannot control the execution order of goroutines

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大