问题描述
我试图了解互斥的工作原理.到目前为止,据我了解,它是用来进行原子操作并同步访问某些数据的.
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.
我在此处构建了队列数据结构的示例: https://github.com/arnauddri/algorithms/blob/master/data-structures%2Fqueue%2Fqueue.go
I built an example of a queue data structure here: https://github.com/arnauddri/algorithms/blob/master/data-structures%2Fqueue%2Fqueue.go
下面是一些代码:
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.
在这里我应该如何使用Mutex?
How should I use the Mutex here?
非常感谢
推荐答案
问题似乎在于您从未实例化互斥体.当您运行 New()
函数时,您正在创建一个空队列,其中包含一个可以引用互斥锁的变量,但是您实际上并没有告诉它这样做,这意味着此时queue.lock == nil
.您可以通过在 New()
函数中添加实例化行来解决此问题.
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)
这是一个有效的游乐场演示: http://play.golang.org/p/Qa6buDaHIj
Here is a playground demo that works: http://play.golang.org/p/Qa6buDaHIj
这篇关于在Go中使用互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!