Goroutines
- goroutines are lightweight threads.
- A goroutine is created by invoking any function with a
go
prefix. go functionName()
Creating a goroutine
To turn any function into a "thread", e.g. a goroutine, add the go
keyword before the function call.
func PrintMessage(message string) {
fmt.Println(message)
}
func main() {
go PrintMessage("Learning Go!")
fmt.Println("Goodbye!")
}
TRY IT OUT
Exercise: Explore goroutines
Change the
PrintMessage
function to print a message 5 times.
Print two additional messages in the
main
function using thePrintMessage
function.
Turn the calls to
PrintMessage
into goroutines.
Question: What is the output?
Consider: How do you know when each goroutine has finished?