Skip to content

Latest commit

 

History

History
65 lines (45 loc) · 1.15 KB

5.1.md

File metadata and controls

65 lines (45 loc) · 1.15 KB

Goroutines

Concepts

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)
}

Exercises

Refactor the above to use an anonymous function.

Tips

  • "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." - Rob Pike

Further Reading


up -- next