stay beam In the virtual machine , Processes usually communicate with each other through message passing , And messaging needs to be replicated, not shared . The message size is small , And only spread between a small number of processes , There is no performance problem . And if we need to share a lot of data between a large number of processes , So messaging is very inefficient and unnecessary .
Erlang It's been considered for a long time , stay beam Added in ETS(erlang term storage), It allows different processes to share data directly . Let's try how it works :
First, let's create a new one ETS surface , Choose to name it :table_a
, The type is set
, Similar to hash table .
:ets.new(:table_a, [:named_table, :set])
We can use :ets.info/1
Function to view the details of this table .
iex(2)> :ets.info :table_a
[
id: #Reference<0.679153060.3873570820.49251>,
read_concurrency: false,
write_concurrency: false,
compressed: false,
memory: 307,
owner: #PID<0.239.0>,
heir: :none,
name: :table_a,
size: 0,
node: :nonode@nohost,
named_table: true,
type: :set,
keypos: 1,
protection: :protected
]
Notice here and socket equally , There needs to be a process as owner, To bind erlang The process world and the outside world (ets,port etc. ) The relationship between , So that link and mointor Mechanisms can be extended to these external components . once owner crash,ets The watch will disappear with it .
":set" How to use types and map almost . default key yes tuple Of the 1 Elements ( from 1 Start counting ).
Let's continue to use BonyTrace Let's test it , See if you really can share data without any messaging .
spawn(fn ->
BonyTrace.start(self())
table = :ets.new(:ets_map, [:named_table, :set, :public])
:ets.insert(table, {"key1", "value1"})
spawn(fn ->
[{"key1", "value1"}] = :ets.lookup(table, "key1")
end)
:timer.sleep(5000)
end)
Be careful ets table Must be set to :public
Can be accessed by other processes . After execution, only the timer is printed out timeout The news of . therefore ets It's really a convenient tool for data sharing between processes .
#PID<0.331.0> RECEIVED +0.000000s
MESSAGE: :timeout