把互斥锁改为读写锁也很简单,只需要把 sync.Mutex 换成 sync.RWMutex ,然后在读操作的地方改为 RLock(),释放读锁改为 RUnlock():
package main
import (
"log"
"sync"
"time"
)
type Account struct {
balance float64
mux sync.RWMutex // 读写锁
}
//
func (a *Account) Deposit(amount float64) {
a.mux.Lock() // 写锁
time.Sleep(time.Second * 2)
a.balance += amount
a.mux.Unlock() // 释放写锁
}
func (a *Account) Balance() (balance float64) {
a.mux.RLock() // 读锁
time.Sleep(time.Second * 2)
balance = a.balance
a.mux.RUnlock() // 释放读锁
return balance
}
func main() {
wg := &sync.WaitGroup{}
user := &Account{}
n := 5
wg.Add(n)
for i := 1; i <= n; i++ {
go func() {
user.Deposit(1000)
log.Printf("写:存款: %v", 1000)
wg.Done()
}()
}
wg.Add(n)
for i := 1; i <= n; i++ {
go func() {
log.Printf("读:余额: %v", user.Balance())
wg.Done()
}()
}
wg.Wait()
}