Go 多线程 (5) RWLock 读写锁

Submitted by Lizhe on Mon, 04/01/2019 - 15:31

读写锁的读行为不会造成同步

但是写行为会同时禁止 读/写 操作

例子很简单, 懒得写了网上找了一个, 下面可以看到读的时候没有阻塞

 

package main

 

import (

    "sync"

    "time"

)

 

var m *sync.RWMutex

 

func main() {

    m = new(sync.RWMutex)

 

    // 多个同时读

    go read(1)

    go read(2)

 

    time.Sleep(2 * time.Second)

}

 

func read(i int) {

    println(i, "read start")

 

    m.RLock()

    println(i, "reading")

    time.Sleep(1 * time.Second)

    m.RUnlock()

 

    println(i, "read over")

}

 

20190401045231

下面是写操作

 

package main

 

import (

    "sync"

    "time"

)

 

var m *sync.RWMutex

 

func main() {

    m = new(sync.RWMutex)

 

    // 写的时候啥也不能干

    go write(1)

    go read(2)

    go write(3)

 

    time.Sleep(5 * time.Second)

}

 

func read(i int) {

    println(i, "read start")

 

    m.RLock()

    println(i, "reading")

    time.Sleep(1 * time.Second)

    m.RUnlock()

 

    println(i, "read over")

}

 

func write(i int) {

    println(i, "write start")

 

    m.Lock()

    println(i, "writing")

    time.Sleep(1 * time.Second)

    m.Unlock()

 

    println(i, "write over")

}

 

20190401052404