Context: https://go.dev/tour/concurrency/1
The problems is that this sample is missing Wait() / Done() calls to guarantee proper execution. If you don't want to introduce this topic at this point my suggestion is to create a slide after this introducing the topic and maybe even asking to verify if the output was correct. Have a nice day!
It must be something like:
package main
import (
"fmt"
"sync"
"time"
)
func say(s string, wg *sync.WaitGroup) {
defer wg.Done() // Decrement the counter when the goroutine finishes
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
var wg sync.WaitGroup // Declare a WaitGroup
wg.Add(1) // Increment the counter for the "world" goroutine
go say("world", &wg) // Pass the address of the WaitGroup
say("hello", nil) // No need for WaitGroup for the "hello" call as it's on the main goroutine
// or you could also use it if you want to be consistent in the function signature
wg.Wait() // Block until the counter becomes zero (i.e., "world" goroutine finishes)
fmt.Println("Both goroutines have completed.")
}
Context: https://go.dev/tour/concurrency/1
The problems is that this sample is missing Wait() / Done() calls to guarantee proper execution. If you don't want to introduce this topic at this point my suggestion is to create a slide after this introducing the topic and maybe even asking to verify if the output was correct. Have a nice day!
It must be something like: