Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wait for a function to finish in golang

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading