doucheng3811 2013-06-21 03:25
浏览 40

为什么当变量为奇数或偶数时,golang sched的运行方式不同? 是巧合还是注定?

I have a sample of golang code as follows(xx.go):

package main

import "runtime"

func main() {
    c2 := make(chan int)

     go func() {
        for v := range c2 {
            println("c2 =", v, "numof routines:", runtime.NumGoroutine())
        }
    }()

    for i:=1;i<=10001;i++{
        c2 <- i
        //runtime.Gosched()
    }
}
  • When the loop count is odd,say 10001,the code will output all the numbers.
  • when the loop count is even ,say 10000,the code will output all the numbers but the last!

Why is that?

I have tested numbers from as small as 2 to as large as 10000,they all obey the above rules!

the ENV is as follows:

uname -a : Linux hadoopnode25232 2.6.18-308.16.1.el5 #1 SMP Tue Oct 2 22:01:43 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux

go version : go version go1.1 linux/amd64

I think it has something to do with the go sched.

I assemble the code:

go tool 6g -S xx.go > xx.s

the only difference between 10000 and 10001 is :

33c33
< 0030 (xx.go:20) CMPQ    AX,$10001
---
> 0030 (xx.go:20) CMPQ    AX,$10000

And,last but not least, when I add runtime.Gosched(),everything runs well.

  • 写回答

3条回答 默认 最新

  • dongsi2317 2013-06-21 03:51
    关注

    You need sleep a second or block a while wait the goroutine is finish!!

    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000