面试题答案
一键面试package main
import (
"fmt"
"sync"
"time"
)
var (
config string
rwMutex sync.RWMutex
)
func readConfig(id int) {
for {
rwMutex.RLock()
fmt.Printf("Goroutine %d reads config: %s\n", id, config)
rwMutex.RUnlock()
time.Sleep(time.Millisecond * 100)
}
}
func writeConfig(id int, newConfig string) {
for {
rwMutex.Lock()
config = newConfig
fmt.Printf("Goroutine %d updates config to: %s\n", id, config)
rwMutex.Unlock()
time.Sleep(time.Second)
}
}
原理解释:
sync.RWMutex
:Go语言提供的读写锁,允许并发读操作,但写操作需要独占锁。- 读操作:在
readConfig
函数中,使用rwMutex.RLock()
获取读锁,允许多个读操作同时进行,因为读操作不会改变数据,所以不会引发资源竞争。读取完成后使用rwMutex.RUnlock()
释放读锁。 - 写操作:在
writeConfig
函数中,使用rwMutex.Lock()
获取写锁,写锁是独占的,此时其他读写操作都无法进行,确保在更新配置信息时不会有其他读或写操作干扰,更新完成后使用rwMutex.Unlock()
释放写锁。通过这种方式,读写锁有效地避免了共享配置信息在读写过程中的资源竞争问题。