[Solved] Need understanding of goroutines [duplicate]


Program execution:

When the function main returns, the program exits. It does not wait
for other (non-main) goroutines to complete.

1- main is goroutine too, you need to wait for other goroutines to finish, and you may use

time.Sleep(5 * time.Second)

for 5 Seconds wait, try it on The Go Playground:

package main

import (
    "fmt"
    "time"
)

func t(i int) {
    fmt.Println("In func t")
    time.Sleep(1 * time.Second)
}

func t1(i int) {
    fmt.Println("In func t1")
    time.Sleep(1 * time.Second)
}

func main() {
    fmt.Println("Hello Good Morning")
    go t(1)
    t1(2)
    time.Sleep(5 * time.Second)
    fmt.Println("End of func main")
}

output:

Hello Good Morning
In func t1
In func t
End of func main

And see Docs:

// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)

2- You may use sync.WaitGroup to wait for other goroutines, try it on The Go Playground:

package main

import (
    "fmt"
    "sync"
    "time"
)

var w sync.WaitGroup

func say(s string) {
    for i := 0; i < 2; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
    w.Done()
}

func main() {
    w.Add(1)
    go say("A")

    w.Add(1)
    say("B")

    w.Wait()
}

output:

B
A
A
B

1

solved Need understanding of goroutines [duplicate]