以下由golang教學專欄跟大家介紹關於golang讀寫鎖,希望對需要的朋友有幫助!
golang讀取寫入鎖,其特徵在於
讀取鎖定:可以同時進行多個協程讀操作,不允許寫入操作
寫鎖定:只允許同時有一個協程進行寫入操作,不允許其他寫入操作和讀取操作
讀寫鎖定共有四個方法
RLock:取得讀取鎖定
RUnLock:釋放讀取鎖定
Lock:取得寫入鎖定
UnLock:釋放寫入鎖定
使用範例如下
package main import ( "fmt" "sync" "time")var gRWLock *sync.RWMutexvar gVar intfunc init() { gRWLock = new(sync.RWMutex) gVar = 1} func main() { var wg sync.WaitGroup go Read(1, &wg) wg.Add(1) go Write(1, &wg) wg.Add(1) go Read(2, &wg) wg.Add(1) go Read(3, &wg) wg.Add(1) wg.Wait() } func Read(id int, wg *sync.WaitGroup) { fmt.Printf("Read Coroutine: %d start\n", id) defer fmt.Printf("Read Coroutine: %d end\n", id) gRWLock.RLock() fmt.Printf("gVar %d\n", gVar) time.Sleep(time.Second) gRWLock.RUnlock() wg.Done() } func Write(id int, wg *sync.WaitGroup) { fmt.Printf("Write Coroutine: %d start\n", id) defer fmt.Printf("Write Coroutine: %d end\n", id) gRWLock.Lock() gVar = gVar + 100 fmt.Printf("gVar %d\n", gVar) time.Sleep(time.Second) gRWLock.Unlock() wg.Done() }
以上是關於golang讀寫鎖的詳細內容。更多資訊請關注PHP中文網其他相關文章!