Created
August 23, 2018 02:56
-
-
Save syfun/fc66579c13680b126affe2c767fff9e2 to your computer and use it in GitHub Desktop.
golang safe heap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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