A goroutine is a lightweight thread of execution. |
|
package main
|
|
import "fmt"
|
|
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
|
|
func main() {
|
|
Suppose we have a function call |
f("direct")
|
To invoke this function in a goroutine, use
|
go f("goroutine")
|
You can also start a goroutine for an anonymous function call. |
go func(msg string) {
fmt.Println(msg)
}("going")
|
Our two goroutines are running asynchronously in
separate goroutines now, so execution falls through
to here. This |
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
|
When we run this program, we see the output of the blocking call first, then the interleaved output of the two gouroutines. This interleaving reflects the goroutines being run concurrently by the Go runtime. |
$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
<enter>
done
|
Next we’ll look at a complement to goroutines in concurrent Go programs: channels. |
Next example: Channels.