Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Golang code different output, why?

Tags:

concurrency

go

I'm trying to execute an example from golang.org : http://tour.golang.org/#63

  • I Have Changed The Code To Test What Exactly Gosched does.*

You could see the output there is: enter image description here

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: enter image description here 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.

like image 771
WoooHaaaa Avatar asked Jan 20 '26 02:01

WoooHaaaa


2 Answers

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.

like image 50
Stephen Weinberg Avatar answered Jan 23 '26 20:01

Stephen Weinberg


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:

  • Go channels
  • http://golang.org/pkg/sync/#WaitGroup

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!