-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_queue.ex
49 lines (39 loc) · 913 Bytes
/
batch_queue.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
defmodule BatchQueue do
use GenServer
def init(queue) do
{:ok, queue}
end
def handle_cast({:add, item}, queue) do
{:noreply, :queue.in(item, queue)}
end
def handle_call(:list, _from, queue) do
{:reply, :queue.to_list(queue), queue}
end
def handle_call(:length, _from, queue) do
{:reply, :queue.len(queue), queue}
end
def handle_call(:fetch, _from, queue) do
with {{:value, item}, new_queue} <- :queue.out(queue) do
{:reply, item, new_queue}
else
{:empty, _} ->
{:reply, :empty, queue}
end
end
# Public API
def start_link() do
GenServer.start_link(__MODULE__, :queue.new())
end
def add(pid, item) do
GenServer.cast(pid, {:add, item})
end
def list(pid) do
GenServer.call(pid, :list)
end
def length(pid) do
GenServer.call(pid, :length)
end
def fetch(pid) do
GenServer.call(pid, :fetch)
end
end