Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elixir
processes

How to send and receive messages in Elixir processes

Educative Answers Team

Processes

Processes are the Elixir equivalent of threads. Threads are used in Concurrent Programming to simultaneously carry out functions.

Inter-process messaging

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"}) end

receive do
  {:hello, msg} -> IO.puts msg
end

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"}) end

receive do
  {:hello, msg} -> IO.puts msg
  {:world, _msg} -> IO.puts "Key matches"
after
  1_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.

RELATED TAGS

elixir
processes
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring