等待互斥量而不获取它

Wait on a mutex without acquiring it

我一直在编写一个小型微服务,因此熟悉 Go 及其并发机制。

在我的程序中,我有一个具有状态的结构,我想同步该状态,以便多个 goroutine 能够读取它,但不能在另一个 goroutine 更新该状态时读取。

最初我认为 RWMutax 是我需要的,但根据文档,只有一个 goroutine 可能在任何给定的时刻获取读锁。我要走这条线:

"If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released."

有什么方法可以在不获取锁的情况下等待互斥锁吗?

大致如下:

type stateful struct {
    state        int
    stateMutex   sync.Mutex
    beingUpdated bool
}

type Stateful interface {
    GetState() int
    SetState(st int)
}

func createStateful (sa string) stateful {
    return server{state: 0, stateMutex: sync.Mutex{}, beingUpdated: false}
}

func (s *stateful) SetState(st int) {
    s.stateMutex.Lock()
    s.beingUpdated = true
    s.state = st
    s.beingUpdated = false
    s.stateMutex.Unlock()
}

func (s *stateful) GetState() bool {
    if s.beingUpdated {
        // wait for s.stateMutex to be unlocked
    }

    return s.state
}

您可能误读了 sync.RWMutex docs:

... The lock can be held by an arbitrary number of readers or a single writer.

因此您的代码可以像这样简化:

type stateful struct {
    l     sync.RWMutex // style: place lock above ...
    state int        //        ... the field it protects
}

func (s *stateful) SetState(st int) {
    s.l.Lock()
    defer s.l.Unlock()

    s.state = st
}

func (s *stateful) GetState() int {
    s.l.RLock()
    defer s.l.RUnlock()

    return s.state
}