Skip to content

Instantly share code, notes, and snippets.

@cloudhead
Created August 7, 2013 12:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudhead/6173733 to your computer and use it in GitHub Desktop.
Save cloudhead/6173733 to your computer and use it in GitHub Desktop.
Blocking queue implementation
package queue
import "sync"
type Message string
type Queue struct {
wmu sync.Mutex
cmu sync.Mutex
slice []*Message
}
func New() *Queue {
q := Queue{slice: []*Message{}}
q.wmu.Lock()
return &q
}
func (q *Queue) Size() int {
q.cmu.Lock()
defer q.cmu.Unlock()
return len(q.slice)
}
func (q *Queue) Push(m *Message) {
q.cmu.Lock()
defer q.cmu.Unlock()
l := len(q.slice)
q.slice = append(q.slice, m)
if l == 0 {
q.wmu.Unlock()
}
}
func (q *Queue) Pop() *Message {
q.cmu.Lock()
defer q.cmu.Unlock()
if len(q.slice) == 0 {
q.wmu.Lock()
}
m := q.pop()
return m
}
func (q *Queue) pop() *Message {
m := q.slice[0]
q.slice = q.slice[1:]
return m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment