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 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: