下面由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()

}