Golang 贪婪线程占用临界区过多问题

 

这是一个创建于 2019-06-07 01:32:39 的文章,其中的信息可能已经有所发展或是发生改变。
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 工作量的两倍!

程序输出如下,


 
 

posted on 2019-11-09 12:13  _Jee  阅读(323)  评论(0编辑  收藏  举报

导航