Skip to content

Instantly share code, notes, and snippets.

@b1naryth1ef
Created September 12, 2013 18:06
Show Gist options
  • Save b1naryth1ef/6541555 to your computer and use it in GitHub Desktop.
Save b1naryth1ef/6541555 to your computer and use it in GitHub Desktop.
This is a simple little Queue with blocking pop abilities built in golang
package queue
import "sync"
type Queue struct {
q []int
size int
lock *sync.Mutex
addlisten chan int
}
func NewQueue() *Queue {
q := Queue{size: 0, lock: new(sync.Mutex)}
q.Clear()
return &q
}
func (q *Queue) Block() {
if q.size <= 0 {
<-q.addlisten
}
}
func (q *Queue) Added() {
q.addlisten <- 1
}
func (q *Queue) LPush(i int) {
q.lock.Lock()
newz := []int{i}
copy(newz, q.q)
q.q = newz
q.size += 1
q.Added()
q.lock.Unlock()
}
func (q *Queue) RPush(i int) {
q.lock.Lock()
q.q = append(q.q, i)
q.size += 1
q.Added()
q.lock.Unlock()
}
func (q *Queue) BRPop() int {
q.Block()
return q.RPop()
}
func (q *Queue) BLPop() int {
q.Block()
return q.LPop()
}
func (q *Queue) RPop() int {
q.lock.Lock()
if q.size <= 0 {
return -1
}
value := q.q[len(q.q)-1]
q.q = q.q[:len(q.q)-1]
q.size -= 1
q.lock.Unlock()
return value
}
func (q *Queue) LPop() int {
q.lock.Lock()
if q.size <= 0 {
return -1
}
value := q.q[0]
q.q = q.q[1:]
q.size -= 1
q.lock.Unlock()
return value
}
func (q *Queue) Clear() {
q.q = make([]int, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment