dongtan7998 2018-03-09 19:46
浏览 46
已采纳

对Go中的Locks / Mutex感到困惑

I am trying to build a map. Normally all read can be done in parallel, except when a write comes, than all reads need to be locked. I thought I understood how Mutex work in go but clearly I do not.

I first tried to use a RWMutex write lock:

type person struct {
    sync.RWMutex
    age int
}

func main() {
    a := person{age: 3}
    fmt.Println(a.age)
    go func() {
        a.Lock()
        time.Sleep(5 * time.Second)
        a.age = 4
        fmt.Println(a.age)
        a.Unlock()
    }()
    fmt.Println(a.age)
    fmt.Println("main", a.age)
    time.Sleep(20 * time.Second)
}

I somewhat expected that the wrote lock would lock the read operation a.age. Instead I got:

3
3
main 3
4

So I decided to add also a read lock:

func main() {
    a := person{age: 3}
    fmt.Println(a.age)
    go func() {
        a.Lock()
        a.RLock()
        time.Sleep(5 * time.Second)
        a.age = 4
        fmt.Println(a.age)
        a.Unlock()
        a.RUnlock()
    }()
    fmt.Println(a.age)
    fmt.Println("main", a.age)
    time.Sleep(20 * time.Second)
}

Even worse, I got:

3
3
main 3

Clearly I am not understanding how this works. Thanks for any help.

  • 写回答

2条回答 默认 最新

  • drmeu26880 2018-03-09 19:51
    关注

    Never double-lock. Your issue is that you're not wrapping the reads at the end of main in locks - if they don't try to establish a lock, there is nothing to prevent them reading while something else writes (even if the write is using a lock). The lock itself is what provides mutual exclusion (MutEx), so you only get it if you use it consistently:

    func main() {
        a := person{age: 3}
        fmt.Println(a.age)
        go func() {
            a.Lock()
            time.Sleep(5 * time.Second)
            a.age = 4
            fmt.Println(a.age)
            a.Unlock()
        }()
        a.RLock()
        fmt.Println(a.age)
        fmt.Println("main", a.age)
        a.RUnlock()
        time.Sleep(20 * time.Second)
    }
    

    There is no magic happening here; it's actually the calls to Lock and RLock that do the locking. If you don't call them, nothing prevents concurrent accesses. When you call Lock, it waits until it can get the lock all to itself, then it locks it and returns. When you call RLock, it waits until there are no write locks, then grabs a (shared) read lock. It is calling those functions which provides mutual exclusion, not any magic happening behind the scenes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题