go - First goroutine example, weird results -
this example taken tour.golang.org/#63
package main import ( "fmt" "time" ) func say(s string) { := 0; < 5; i++ { time.sleep(100 * time.millisecond) fmt.println(s) } } func main() { go say("world") say("hello") }
the output
hello world hello world hello world hello world hello
why world
printed 4
times instead of 5
?
edit: answer can quoted golang specification:
program execution begins initializing main package , invoking function main. when function main returns, program exits. not wait other (non-main) goroutines complete.
when main function ends program ends, i.e. goroutines terminated. main terminates before go say("world")
done. if sleep time @ end of main should see last world.
Comments
Post a Comment