Search⌘ K

Solution Review: Multiplication Table

Understand the use of WaitGroup to manage concurrency in Go by reviewing a multiplication table example. Learn how goroutines are launched, synchronized, and coordinated to ensure ordered output, helping you grasp key concurrency patterns in practical coding.

We'll cover the following...

Here is the code to the challenge in the previous lesson:

Go (1.6.2)
package main
import ( "fmt"
"sync"
"time")
func printTable(n int, wg *sync.WaitGroup) {
for i := 1; i <= 12; i++ {
fmt.Printf("%d x %d = %d\n", i, n, n*i)
time.Sleep(50 * time.Millisecond)
}
wg.Done()
}
func main() {
var wg sync.WaitGroup
for number := 2; number <= 12; number++ {
wg.Add(1)
go printTable(number,&wg)
}
wg.Wait()
}

So we added a WaitGroup from the sync package on line 15 named wg. At every iteration in the for-loop in the main routine, we increment the counter of wg on line 18. In the next step on line 19, we execute the ...