gogoroutinesubroutinedefer-keyword

Will defer be waiting until subroutine finishes execution?


I have such function:

func TestDefer(lock sync.RWMutex, wait time.Duration) {

    lock.Lock()
    defer lock.Unlock()

    // start goroutine 
    go func() {
        time.Sleep(wait)
    }()
}

I am eager to know when lock.Unlock() will be executed? Is it synchronized with subroutine go func() ? Will it be waiting until it finishes?


Solution

  • No. Defer will not wait for your go routine to finish. IF you want to do that, wait till the go routine is done executing using sync.WaitGroup.

    func TestDefer(lock sync.RWMutex, wait time.Duration) {
        wg := new(sync.WaitGroup)
        lock.Lock()
        defer lock.Unlock()
    
        wg.Add(1)
        // start goroutine 
        go func() {
            defer wg.Done()
            time.Sleep(wait)
        }()
        wg.Wait()
    }