Reputation: 20450
I'm trying to execute an example from golang.org : http://tour.golang.org/#63
You could see the output there is:
hello
hello
hello
hello
hello
But when i copy those code to my Mac OS X 10.8(Go version 1.0.3), the output has changed:
xxxxxx$ go version
go version go1.0.3
xxxxxx$ go run goroutine.go
hello
world
hello
world
hello
world
hello
world
hello
world
According to this answer, i should use runtime.GoSched, but in fact i needn't.So i believe something goes wrong.
Please help me with this, many thanks.
Upvotes: 3
Views: 785
Reputation: 146
It is because you are calling a goroutine which runs outside your programming environment. Literally, two threads are getting executed concurrently and the output going to be random is obvious.
Upvotes: 0
Reputation:
The Go Tour code is only an introductory example. The code is simplistic and incorrect. GoTour63 gives the following output (line numbers added):
1 hello
2 world
3 hello
4 world
5 hello
6 world
7 hello
8 world
9 hello
The program should print 10 lines. Notice that the line 10 world
is missing. Maybe it is intentional and the user is expected to notice this and to investigate the cause of the problem. The section Program execution in the language specification states the following:
When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.
This statement explains why the program is printing less than 10 lines.
Correct Go programs usually use:
Upvotes: 2
Reputation: 53418
The issue here is you have two different implementations.
Locally, your code yields to the scheduler each time fmt.Println is called. Println does a write to stdout which does a syscall. All syscalls yield the same way runtime.Gosched does.
play.golang.org is a black box. We don't actually know how it works. However, from the example you gave, it appears play does not do a syscall when fmt.Println is called. This makes sense. They probably replaced os.Stdout with a buffer to hold what is printed.
Upvotes: 4