Part 1 , Part 2 , Part 3 , Part 4 , Part 5
Goroutines can be used to take advantage of CPUs with multiple processors. Starting a Goroutine using the “go” keyword, will start execution on a thread in parallel if a thread is available. You will need to make sure that your main function does not exit before all the goroutines finish their work.
Playground: https://go.dev/play/p/FTJLzwY34l2
package main
import (
"fmt"
"sync"
)
func main() {
wg := sync.WaitGroup{}
// use many goroutines to compute the product of two numbers
for i := 0; i < 100; i++ {
for j := 0; j < 100; j++ {
// capture the value of i and j
// otherwise, the value of i and j will be changed
// before the goroutine is executed
i := i
j := j
// add a goroutine to the wait group
wg.Add(1)
go func() {
// defer the decrement of the wait group
defer wg.Done()
// compute the product
product := i * j
// print the product
fmt.Println(i, j, product)
}()
}
}
// ensure that goroutines are executed
// otherwise, the program will exit
// before all the goroutines are executed
wg.Wait()
fmt.Println("Done")
}