package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
var sharedLock sync.Mutex
const runtime = 1 * time.Second
func main() {
wg.Add(2)
greedyWorker := func() {
defer wg.Done()
var count int
for begin := time.Now(); time.Since(begin) <= runtime; {
sharedLock.Lock()
time.Sleep(3 * time.Nanosecond)
sharedLock.Unlock()
count++
}
fmt.Printf("Greedy worker was able to execute %v work loops\n", count)
}
politeWorker := func() {
defer wg.Done()
var count int
for begin := time.Now(); time.Since(begin) <= runtime; {
sharedLock.Lock()
time.Sleep(1 * time.Nanosecond)
sharedLock.Unlock()
sharedLock.Lock()
time.Sleep(1 * time.Nanosecond)
sharedLock.Unlock()
sharedLock.Lock()
time.Sleep(1 * time.Nanosecond)
sharedLock.Unlock()
count++
}
fmt.Printf("Polite worker was able to execute %v work loops\n", count)
}
go greedyWorker()
go politeWorker()
wg.Wait()
}
贪婪的 worker 会贪婪地抢占共享锁,以完成整个工作循环,而平和的 worker 则试图只在需要时锁定。两种 worker 都做同样多的模拟工作(sleeping 时间 为 3ns),但是你可以看到,在同样的时间里,贪婪的 worker 工作量几乎是 平和的 worker 工作量的两倍!
程序输出如下,