Skip to content

Instantly share code, notes, and snippets.

@syfun
Created August 23, 2018 02:56
Show Gist options
  • Save syfun/fc66579c13680b126affe2c767fff9e2 to your computer and use it in GitHub Desktop.
Save syfun/fc66579c13680b126affe2c767fff9e2 to your computer and use it in GitHub Desktop.
golang safe heap
package main
import (
"container/heap"
"sync"
)
// SafeHeap implement a concurrent safe heap.
type SafeHeap struct {
sync.RWMutex
h heap.Interface
}
// Push x into heap.
func (h *SafeHeap) Push(x interface{}) {
h.Lock()
defer h.Unlock()
heap.Push(h.h, x)
}
// Pop the minimum or maximum.
func (h *SafeHeap) Pop() interface{} {
h.Lock()
defer h.Unlock()
return heap.Pop(h.h)
}
// Len get length.
func (h *SafeHeap) Len() int {
h.RLock()
defer h.RUnlock()
return h.h.Len()
}
// New create new safe heap.
func New(h heap.Interface) *SafeHeap {
sh := &SafeHeap{h: h}
heap.Init(sh.h)
return sh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment