Skip to content

Instantly share code, notes, and snippets.

@blanchonvincent
Created August 16, 2019 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blanchonvincent/51d185386de69e86c1b0f04c424bc97a to your computer and use it in GitHub Desktop.
Save blanchonvincent/51d185386de69e86c1b0f04c424bc97a to your computer and use it in GitHub Desktop.
Medium - Monitor pattern - solution with channel
type Item = int
type waiter struct {
n int
c chan []Item
}
type state struct {
items []Item
wait []waiter
}
type Queue struct {
s chan state
}
func NewQueue() *Queue {
s := make(chan state, 1)
s <- state{}
return &Queue{s}
}
func (q *Queue) Put(item Item) {
s := <-q.s
s.items = append(s.items, item)
for len(s.wait) > 0 {
w := s.wait[0]
if len(s.items) < w.n {
break
}
w.c <- s.items[:w.n:w.n]
s.items = s.items[w.n:]
s.wait = s.wait[1:]
}
q.s <- s
}
func (q *Queue) GetMany(n int) []Item {
s := <-q.s
if len(s.wait) == 0 && len(s.items) >= n {
items := s.items[:n:n]
s.items = s.items[n:]
q.s <- s
return items
}
c := make(chan []Item)
s.wait = append(s.wait, waiter{n, c})
q.s <- s
return <-c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment