I'm trying to understand how can I fix this race condition for below code.
sayHello := func() {
fmt.Println("Hello from goroutine")
}
go sayHello()
time.Sleep(1)
fmt.Println("Hello, playground")
Expectation: I just want to know whats the best solution, should I use WaitGroup or is there any better solution ?
So I came up with below solution :
var wg sync.WaitGroup
//defer wg.Wait()
sayHello := func() {
defer wg.Done()
fmt.Println("Hello from goroutine")
}
wg.Add(1)
go sayHello()
wg.Wait()
fmt.Println("Hello, playground")
But its blocking the main goroutine until code is executed !
As well, if I use defer wg.Wait()
the output is different ! https://play.golang.org/p/_xkLb7HvNF8
Race condition I meant where go sayHello()
never even gets executed, cause the main func will finish executing before the goroutine even started. Hence it creates a race condition if I try to put a time.Sleep