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.