1

I run the following Go code 10 times:

package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("Hello")
    fmt.Println("World")
    time.Sleep(1 * time.Millisecond)
}

The output is always "World" first:

World
Hello

Does it manifest the goroutine will execute unitl there is a block in main routine? What is the execution time point of goroutine?

Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
  • Maybe there is a overhead to start the goroutine that is large enough to put it in the second place. A 1ms sleep before the `fmt.Println` prints `Hello\nWorld\n`. –  Jun 19 '15 at 10:38
  • 5
    @Tichodroma: assuming GOMAXPROCS=1, `time.Sleep` just switches context to another routine. This is one of these _points_ where scheduler is happy to do so. (see: http://stackoverflow.com/questions/15771232) – tomasz Jun 19 '15 at 10:43

1 Answers1

5

What is the execution time point of goroutine?

The compiler will insert yield points into your program at different locations where it seems adequate. For example, in some function calls and seemingly tight loops. Also, a goroutine will yield when blocking on a syscall. So your program will probably yield execution over to the second goroutine when the first goroutine reaches fmt.Println("World") and enters a write syscall. After that non-determinism ensues because we don't know how long this syscall will take.

This, however, is an implementation detail and you should not be concerned with it. When talking about parallelism, the only timing guarantees (i.e. "happens before") you have are those provided by concurrency primitives like those from the standard library's sync/atomic package.

TL;DR: Don't rely on yield points for your program to work correctly.

thwd
  • 23,956
  • 8
  • 74
  • 108
  • 1
    Especially **don't rely on yield points for your program to work correctly**. If you do, it might possibly work now, but there's *no guarantee* it will still work in future, or on a different machine with a faster cpu, or on a different OS, or on a system with more I/O load, etc etc. – Rick-777 Jun 22 '15 at 09:08