我一直在编写一个小型微服务,以便熟悉Go及其并发机制。
在我的程序中,我有一个具有状态的结构,并且我想同步该状态,以便多个goroutine能够读取它,但当另一个goroutine正在更新该状态时,则不能。
最初,我认为RWMutax是我需要的,但是根据文档,只有一个goroutine可以在任何给定的哀悼中获得读锁定。我要说这句话:
“如果一个 goroutine 拿着一个 RWMutex 进行读取,而另一个 goroutine 可能会调用 Lock,那么在释放初始读锁定之前,没有 goroutine 应该能够获得读锁定。
有没有办法在不获取锁的情况下等待互斥锁?
大致如下:
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
}
FFIVE
相关分类