I'm a newbie on Golang and I just learnt about the conception Goroutine with an example below:
package main
import "fmt"
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("direct")
go f("goroutine")
go f("goroutine2")
go func(msg string) {
fmt.Println(msg)
}("going")
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
Here is one result of execution:
direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine2 : 0
goroutine2 : 1
goroutine2 : 2
goroutine : 1
goroutine : 2
going
done
I can see that goroutine
and goroutine2
appeared alternately. So for me it looks like the multi-threading.
I've been told that Goroutine is lighter than thread. So I just want to know what is exactly the difference between them, why doesn't Go use the routine instead of multi-thread?