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()

}