Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
Rudziankoŭ Avatar asked Sep 12 '25 01:09

Rudziankoŭ


2 Answers

No, as soon as the go statement finishes its execution (that is, the Go runtime creates a new goroutine and puts it on some run queue), the execution of the function continues, and since the function's body ends there, the functions deferred in it will run.

Synchronization between goroutines only ever happens explicitly—by means of channel operations of using primitives from the packages of the sync hierarchy.

like image 78
kostix Avatar answered Sep 14 '25 21:09

kostix


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()
}
like image 41
vedhavyas Avatar answered Sep 14 '25 19:09

vedhavyas