doudou5023 2015-01-30 19:41
浏览 37
已采纳

在Go中使用互斥锁

I am trying to understand how mutexes work. From my understanding so far, it is made to carry atomic operations and synchronize access to some data.

I built an example of a queue data structure here: https://github.com/arnauddri/algorithms/blob/master/data-structures%2Fqueue%2Fqueue.go

Here is a bit of the code:

package queue

import "sync"

type Queue struct {
    queue []interface{}
    len   int
    lock  *sync.Mutex
}

func New() *Queue {
    queue := &Queue{}
    queue.queue = make([]interface{}, 0)
    queue.len = 0

    return queue
}

func (q *Queue) Push(el interface{}) {
    q.lock.Lock()
    defer q.lock.Unlock()

    q.queue = append(q.queue, el)
    q.len++
}

However when I try to create a queue and push an item to it I get a runtime error:

q := New()
q.Push(1)

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference

I really don't understand what is happening here.

How should I use the Mutex here?

Many thanks

  • 写回答

3条回答 默认 最新

  • du_1993 2015-01-30 19:45
    关注

    Looks like the issue is that you're never instantiating the mutex. When you run the New() function you're creating an empty Queue with a variable that can reference a mutex, but you never actually tell it to do so, which means that at this point queue.lock == nil. You can fix this by adding in an instantiation line to your New() function.

    queue.lock = new(sync.Mutex)
    

    Here is a playground demo that works: http://play.golang.org/p/Qa6buDaHIj

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序