Rudziankoŭ
Rudziankoŭ

Reputation: 11251

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?

Upvotes: 4

Views: 3084

Answers (2)

vedhavyas
vedhavyas

Reputation: 1151

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

Upvotes: 5

kostix
kostix

Reputation: 55443

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.

Upvotes: 7

Related Questions