I have the following code in golang:
func A(){
go print("hello")
}
func main() {
A()
// here I want to wait for the print to happen
B()
}
How can I somehow ensure that B() will be executed only after the print has happened?
>Solution :
Use sync.Mutex
var l sync.Mutex
func A() {
go func() {
print("hello")
l.Unlock()
}()
}
func B() {
print("world")
}
func TestLock(t *testing.T) {
l.Lock()
A()
l.Lock()
// here I want to wait for the print to happen
B()
l.Unlock()
}
Use sync.WaitGroup
var wg sync.WaitGroup
func A() {
go func() {
print("hello")
wg.Done()
}()
}
func B() {
print("world")
}
func TestLock(t *testing.T) {
wg.Add(1)
A()
wg.Wait()
// here I want to wait for the print to happen
B()
}
Use chan
func A() chan struct{} {
c := make(chan struct{})
go func() {
c <- struct{}{}
print("hello")
}()
return c
}
func B() {
print("world")
}
func TestLock(t *testing.T) {
c := A()
// here I want to wait for the print to happen
<-c
B()
}