dpvv37755 2019-01-08 13:34
浏览 328
已采纳

在golang中仔细检查了锁定-为什么需要mutex.RLock()?

I have a piece of code from this website which has double checked locking for initialization of an object.

func checkSyncProducer() {
    mutex.RLock()
    if syncProducer == nil {
        mutex.RUnlock()
        mutex.Lock()
        defer mutex.Unlock()
        if syncProducer == nil {
            syncProducer  = createSyncKafkaProducer() //this func will initialize syncProducer.
        }
    } else {
        defer mutex.RUnlock()
    }
}

This piece of code has mutex.RLock() before first nil check.

Why is that required? (it is explained in the page but I couldn't understand) And doesn't it add overhead becuase everytime checkSyncProducer is called read lock will be taken and released.

Should there be one more nil check before acquiring read lock like:

func checkSyncProducer() {
    if syncProducer == nil {
        mutex.RLock()
        if syncProducer == nil {
            mutex.RUnlock()
            mutex.Lock()
            defer mutex.Unlock()
            if syncProducer == nil {
                createSyncKafkaProducer()
            }
        } else {
            defer mutex.RUnlock()
        }
    }
}

First nil check will ensure that RLock is not taken unnecessarily. Am I correct?

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 香农解码的代码问题,无法输出解码结果
      • ¥15 内网同一网段设备和wifi隔离
      • ¥15 Python操作注册表
      • ¥45 入门级别的一段VUE前端拍照像后端发送请求的代码,帮排错
      • ¥15 anaconda打开spyder后一直闪退,不知道怎么办
      • ¥15 解决迷宫问题中无法运行的问题
      • ¥15 关于aspnetcore中使用mqttnet库的entire
      • ¥15 关于#python#的问题,请各位专家解答!
      • ¥100 关于远控软件的两个问题
      • ¥15 基于STM32的AD8232心电采集装置设计