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