dongzhi6927 2017-05-27 10:36
浏览 208

初始化RWMutex在Golang中崩溃?

The following code crashes with the following error, why??

package main

import (
    "sync"

)

var foo *sync.RWMutex

func main() {
    foo.Lock()
}

outputs:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x8125c]

goroutine 1 [running]:
sync.(*RWMutex).Lock(0x0, 0x104000f0)
    /usr/local/go/src/sync/rwmutex.go:86 +0x1c
main.main()
    /tmp/sandbox093456788/main.go:11 +0x20

Program exited.

it will not happen, when you use one of the following lines

var foo = new(sync.RWMutex)
var foo sync.RWMutex

for the initialization of the foo variable.

  • 写回答

1条回答 默认 最新

  • duanhunlou7051 2017-05-27 11:19
    关注

    The mutexes are generally designed to work without any type of initialization. That is, a zero valued mutex is all you need to use them. To fix your program, declare foo as a value. Not a pointer to a mutex:

    var foo sync.RWMutex
    
    func main() {
        foo.Lock()
    }
    

    When you declare foo as a pointer:

    var foo *sync.RWMutex
    

    foo is a zero valued pointer (to type sync.RWMutex), i.e. it does not point to a valid mutex value. foo is nil. That's why you get the nil pointer exception when calling a method.

    However, note that to share the mutex between goroutines/functions, you're going to have to pass them as pointers, after they have been initialized (like above), or they'll not be shared.

    From the docs:

    An RWMutex must not be copied after first use.

    Docs: https://golang.org/pkg/sync/#RWMutex

    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加