Home > Software design >  Why does this not print out 20 greetings?
Why does this not print out 20 greetings?

Time:10-06

I'm learning Golang and am struggling to understand why this isn't printing out 20 greetings even though I'm calling the function twice with 10 times each.

package main

import (
    "log"
    "math/rand"
    "time"
)

func SayGreetings(greeting string, times int) {
    for i := 0; i < times; i   {
        log.Println(greeting)
        d := time.Second * time.Duration(rand.Intn(5)) / 2
        time.Sleep(d) // sleep for 0 to 2.5 seconds
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    log.SetFlags(0)
    go SayGreetings("hi!", 10)
    go SayGreetings("hello!", 10)
    time.Sleep(2 * time.Second)
}

CodePudding user response:

Very simple to explain. You call SayGreetings twice with the go keyword, which causes two concurrent executions of the SayGreetings function. At the end you don't wait until both functions finish! Your code only waits for 2 seconds after calling both functions, each function waits for more than two seconds. So you either increase the wait time in main, or wait until both functions finish

Your issue is similar to Wait for concurrent workers to finish before exiting

  •  Tags:  
  • go
  • Related