goroutines are functions that run concurrently:
package main
import (
"fmt"
"time"
)
func main() {
go sayHi("Andrew")
go sayHi("Beavis")
go sayHi("Cory")
time.Sleep(1 * time.Second)
}
func sayHi(name string) {
fmt.Printf("Hi %s\n", name)
}
If this is run 3 times, there could be 3 different orderings of names because each sayHi is run concurrently.
time.Sleep
is required at the end because if main
exits while the goroutines are running, the program will end.
Next we will take a look at how to orchestrate goroutines and share state. Before we move on, we are going to refactor the above example:
package main
import (
"fmt"
"time"
)
func main() {
for _, name := range []string{"Andrew", "Beavis", "Cory"} {
go sayHi(n)
}
time.Sleep(1 * time.Second)
}
func sayHi(n string) {
fmt.Println(n)
}
Refactor the above to use an anonymous function.
- "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." - Rob Pike