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?
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.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With