Elixir Concurrency
Concurrency
Elixir was designed for concurrent programming. You will quickly learn how to divide your program into communicating processes and thereby give it far better structure. Try the following:
The IO.puts
procedure will output the string to the stdout and insert the x
value by means of string interpolation. Compile and load the above module in the Elixir interactive shell iex
(the returned PID number may be different):
The variable p
is now bound to the process identifier of spawned process. The process was created and called the procedure hello/0
(this is how we name a function with zero arguments). It is now suspended waiting for incoming messages. In the same Elixir iex
shell execute the command:
Now register the process identifier under the name :foo
after having started a new process (the one above died after having received the message):
Tic-Tac-Toe
In the example above the only thing we sent was a string but we can send arbitrary complex data structures. The receive
statement can have several clauses that try to match incoming messages. Only if a match is found will a clause be used. Try this:
Then in the iex
shell execute the following commands:
In what order where they received by the process? Note how messages are queued and how the process selects in what order to process them.
Last updated