我一直在編寫一個小型微服務,以便熟悉Go及其并發(fā)機制。在我的程序中,我有一個具有狀態(tài)的結構,并且我想同步該狀態(tài),以便多個goroutine能夠讀取它,但當另一個goroutine正在更新該狀態(tài)時,則不能。最初,我認為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}
1 回答

FFIVE
TA貢獻1797條經驗 獲得超6個贊
您可能誤讀了同步。RWMutex docs:
...鎖可以由任意數量的讀取器或單個寫入器持有。
所以你的代碼簡化如下:
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
}
- 1 回答
- 0 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消