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

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -