-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcatshop_clerk_2_1.erl
85 lines (58 loc) · 1.87 KB
/
catshop_clerk_2_1.erl
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
-module(catshop_clerk_2_1).
-import(rand, [uniform/1]).
-export([start_shift/0, order_cat/1, return_cat/2, end_shift/1, loop/1]).
%%% Client API
start_shift() -> spawn_link(?MODULE, loop, [[]]).
order_cat(ClerkPID) ->
Ref = erlang:monitor(process, ClerkPID),
ClerkPID ! {self(), order},
receive
{cat, Name, Color} ->
erlang:demonitor(Ref),
{cat, Name, Color};
{'DOWN', Ref, process, ClerkPID, Reason} ->
erlang:error(Reason)
after 5000 ->
erlang:demonitor(Ref),
erlang:error(timeout)
end.
end_shift(ClerkPID) ->
Ref = erlang:monitor(process, ClerkPID),
ClerkPID ! {self(), terminate},
receive
ok ->
erlang:demonitor(Ref),
ok;
{'DOWN', Ref, process, ClerkPID, Reason} ->
erlang:error(Reason)
after 5000 ->
erlang:demonitor(Ref),
erlang:error(timeout)
end.
return_cat(ClerkPID, Cat) ->
ClerkPID ! {return, Cat},
ok.
%%% Server Funktionen
loop(Catlist) ->
receive
{ClientPID, order} ->
if
Catlist == [] ->
ClientPID ! make_cat(),
loop(Catlist);
Catlist =/= [] ->
ClientPID ! hd(Catlist),
loop(tl(Catlist))
end;
{ClientPID, terminate} ->
ClientPID ! ok;
{return, {cat, Name, Color}} ->
loop([{cat, Name, Color} | Catlist])
end.
%%% Private Funktionen
make_cat() ->
Name = lists:nth(uniform(11), names()),
Color = lists:nth(uniform(6), colors()),
{cat, Name, Color}.
names() -> ["Karl", "Peter", "Kai-Uwe", "Uwe-Kai", "Nils", "Martha", "Elisabeth", "Jonas", "Gerda", "Katharina", "Franziska"].
colors() -> [black, blue, white, orange, pink, brown].