Created
August 16, 2019 07:26
-
-
Save blanchonvincent/51d185386de69e86c1b0f04c424bc97a to your computer and use it in GitHub Desktop.
Medium - Monitor pattern - solution with channel
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
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