在Go语言中,可以使用sync包中的Mutex类型来实现互斥锁,使用sync包中的RWMutex类型来实现读写锁。下面是它们的基本用法示例:
package main
import (
"fmt"
"sync"
)
var mutex sync.Mutex
var count int
func increment() {
mutex.Lock()
defer mutex.Unlock()
count++
}
func main() {
for i := 0; i < 10; i++ {
go increment()
}
// 等待所有goroutine执行完毕
mutex.Lock()
defer mutex.Unlock()
fmt.Println(count)
}
package main
import (
"fmt"
"sync"
)
var rwMutex sync.RWMutex
var data map[string]string
func readData(key string) {
rwMutex.RLock()
defer rwMutex.RUnlock()
fmt.Println(data[key])
}
func writeData(key, value string) {
rwMutex.Lock()
defer rwMutex.Unlock()
data[key] = value
}
func main() {
data = make(map[string]string)
writeData("key1", "value1")
for i := 0; i < 10; i++ {
go readData("key1")
}
// 等待所有goroutine执行完毕
rwMutex.Lock()
defer rwMutex.Unlock()
for k, v := range data {
fmt.Println(k, v)
}
}
在使用互斥锁和读写锁时,需要注意以下几点: