Go RWMutex 读写锁

Go About 793 words

RWMutex

可并行读,读写互斥。有写时,所有读都暂停。

类似于Java中的ReentrantReadWriteLock

代码

var rwMutex sync.RWMutex

func main() {
    amount := 0
    for i := 0; i < 10; i++ {
        go Read(&amount)
    }
    for i := 0; i < 10; i++ {
        go Write(&amount)
    }

    time.Sleep(time.Second * 3)

    Read(&amount)
}

func Read(amount *int) {
    rwMutex.RLock()
    defer rwMutex.RUnlock()
    println(time.Now().String(), "#", *amount)
}

func Write(amount *int) {
    rwMutex.Lock()
    defer rwMutex.Unlock()
    *amount += 1
}

读锁

RLock上读锁,RUnlock解除读锁。

func Read(amount *int) {
    rwMutex.RLock()
    defer rwMutex.RUnlock()
    println(time.Now().String(), "#", *amount)
}

写锁

Lock上写锁,Unlock解除写锁。

func Write(amount *int) {
    rwMutex.Lock()
    defer rwMutex.Unlock()
    *amount += 1
}
Views: 667 · Posted: 2023-10-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh