I was learning Go
Channel
. I made a below small program in Go
package main
import "fmt"
func sample(mychan chan string) {
fmt.Println("Go Go Go Go")
fmt.Println("message received from channel is ", <-mychan)
}
func main() {
messageChan := make(chan string)
go sample(messageChan)
messageChan <- "hello"
}
What's happening is that sometimes it shows "message received ..." statement. And sometimes it does not show. And it always shows "Go Go Go .." statement. Then why does it skips "message received " statement. What is this behaviour. I am confused.
When your main()
finishes the program is terminated before sample()
goroutine can receive (or print) the message. This is really non-deterministic behavior depending on scheduling and that's why you sometimes see the message.
You can modify your program to wait for sample()
to finish by using sync.WaitGroup
. The only significant change I made besides that is I now call sample()
from anonymous goroutine go func() {...}()
to be able to do wg.Done()
once sample()
itself finishes.
See https://pkg.go.dev/sync#WaitGroup for further explanation what WaitGroup
does.
package main
import (
"fmt"
"sync"
)
func sample(mychan chan string) {
fmt.Println("Go Go Go Go")
fmt.Println("message received from channel is ", <-mychan)
}
func main() {
messageChan := make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go func() {
sample(messageChan)
defer wg.Done()
}()
messageChan <- "hello"
wg.Wait()
}