Concurrency

Elixir Processes

Using Processes

Elixir processes are lightweight actors for concurrency.

Introduction to Elixir Processes

Elixir processes are one of the core features of the Elixir language, providing a simple yet powerful way to handle concurrency. They are based on the Actor model, where each process is a separate entity that can send and receive messages.

Unlike operating system processes, Elixir processes are lightweight and have minimal overhead, making it possible to run thousands of them concurrently.

Creating a Simple Process

Creating a process in Elixir is straightforward. You can use the spawn function to start a new process. The spawn function takes a function as an argument and runs it in a separate process.

In this example, the say_hello function starts a new process that outputs a message to the console. The spawn/1 function takes an anonymous function that executes the desired code in a new process.

Sending and Receiving Messages

Processes in Elixir communicate by sending and receiving messages. You can use the send function to send a message to a process, and the receive block to handle incoming messages.

In this example, the Messenger module defines a listen function that waits for messages. It sends a reply when it receives a {:hello, sender} tuple. The process ID of the listener is obtained using spawn/3, and a message is sent to it using the send function.

Linking Processes

Elixir allows processes to be linked so that if one process crashes, linked processes are notified. This is useful for monitoring and managing process failures.

Use the spawn_link function to create a linked process.

In this example, the crash function spawns a new process that raises an exception. Since we used spawn_link, the crash will also cause the calling process to crash, demonstrating how linked processes share their termination status.

Previous
Strings