Created
August 7, 2013 12:43
-
-
Save cloudhead/6173733 to your computer and use it in GitHub Desktop.
Blocking queue implementation
This file contains hidden or 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 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