-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocesses.ex
68 lines (53 loc) · 1.08 KB
/
processes.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# basic spawn
defmodule Echoer do
def echo do
receive do
{:hello, x} ->
IO.puts "Echo #{inspect(x)}"
end
end
end
pid = spawn(Echoer, :echo, [])
# send a message
pid <- :no_match # => :no_match
pid <- {:hello, :process} # => {:hello, :process}
# "Echo :process"
# now it's done
pid <- {:hello, :again?} # => {:hello, :again?}
# recursion to keep alive (tail recursion!)
defmodule Echoer do
def echo do
receive do
{:hello, x} ->
IO.puts "Echo #{inspect(x)}"
end
echo
end
end
# example with parameters?
# passing pid to allow processes to return back
defmodule Child do
def question do
receive do
{:yo_dawg, caller} ->
caller <- :i_heard_you_liked_processes
end
end
end
pid = spawn(TiredMeme, :create_child, [])
# registry
Process.register(pid, :memorable_name_goes_here)
:memorable_name_goes_here <- :message
# queueing
defmodule Q do
def wait_a_bit do
:timer.sleep 10000
handle_msgs
end
def handle_msgs do
receive do
x -> IO.puts("Got #{inspect(x)}")
end
handle_msgs
end
end