關於golang讀寫鎖

2020-09-25 15:00:17
下面由欄目給大家介紹關於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讀寫鎖的詳細內容,更多請關注TW511.COM其它相關文章!