Processes are the Elixir equivalent of threads. Threads are used in Concurrent Programming to simultaneously carry out functions.
Messages can be transmitted among different processes in Elixir. This operation is done using the send
function and the receive do
operator.
processId = self()spawn fn -> send(processId, {:hello, "Message sent and received"}) endreceive do{:hello, msg} -> IO.puts msgend
In this program, a process is started using the spawn
function. This process sends a message with the key :hello
to the main thread. The main thread’s process ID is obtained using the self()
function and stored in the processId
variable.
Processes can also be programmed to wait a certain amount of time for a message, and then do something else if no message that matches the possible keys arrives.
processId = self()spawn fn -> send(processId, {:nonmatchingkey, "Message"}) endreceive do{:hello, msg} -> IO.puts msg{:world, _msg} -> IO.puts "Key matches"after1_000 -> IO.puts "No matching key received within 1 second"end
This example does the same things as the previous example, except there is a timer on the receiving operator. When the timer runs out, it outputs the “no” message with any matching key that has been received. The spawned process does send a message; however, this message’s key does not match with any of the set keys.
Free Resources