在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)
}
}
在使用互斥鎖和讀寫鎖時,需要注意以下幾點: