Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
import "sync"
func main() {
var wg, mu, n = sync.WaitGroup{}, sync.Mutex{}, 0
wg.Go(func() { mu.Lock(); n++; mu.Unlock() })
wg.Go(func() { mu.Lock(); n++; mu.Unlock() })
wg.Wait()
fmt.Println(n)
}2
- Expecting
1:mu.Locklets only one goroutine runn++at a time, so the second one sees1and no increment is lost. - Expecting a deadlock: the second
Lockonly waits until the first goroutine callsUnlock, then it goes on.
- What could the program print without
mu.Lockandmu.Unlock? - Why must
wg.Wait()come beforefmt.Println(n)?