共計 926 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Go 語言中,可以使用 sync 包中的 Mutex 類型來實現(xiàn)互斥鎖,使用 sync 包中的 RWMutex 類型來實現(xiàn)讀寫鎖。下面是它們的基本用法示例:
- 互斥鎖(Mutex):
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 執(zhí)行完畢
mutex.Lock()
defer mutex.Unlock()
fmt.Println(count)
}
- 讀寫鎖(RWMutex):
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 執(zhí)行完畢
rwMutex.Lock()
defer rwMutex.Unlock()
for k, v := range data {fmt.Println(k, v)
}
}
在使用互斥鎖和讀寫鎖時,需要注意以下幾點:
- 互斥鎖適用于讀寫互斥的情況,讀寫鎖適用于讀多寫少的情況。
- 對于互斥鎖,使用 Lock() 方法獲取鎖,使用 Unlock() 方法釋放鎖。
- 對于讀寫鎖,使用 RLock() 方法獲取讀鎖,使用 RUnlock() 方法釋放讀鎖;使用 Lock() 方法獲取寫鎖,使用 Unlock() 方法釋放寫鎖。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完