Goroutines
Lightweight concurrency and threading
Go routines are essentially lightweight threads managed by the go runtime. We use the go
keyword in front of a function to specify that it is a routine
package main
import (
"fmt"
"time"
)
func main() {
// run the say function in a goroutine
go say("world")
say("hello")
}
// intentionally delay the say function, so simulate a long
// running proccess
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
$ go run goroutine_demo.go
hello
world
world
hello
world
hello
world
hello
world
hello
Last updated