Welcome to your first step into Elixir’s concurrency model. In this unit, you will see how to start (spawn) lightweight processes and let them run at the same time. You and I will walk through a small program that launches several workers concurrently while the main program keeps going.
We start by defining a simple worker function. It prints a start message, simulates work for a second, and then prints a finish message.
Explanation:
Worker.work/1is a regular function; we will run it in separate processes soon.Process.sleep(1000)pauses the process for 1 second to simulate work. It does not block other processes.
Now we launch three processes, each running the worker function with a different name.
Explanation:
spawnstarts a new, separate process that runs the anonymous function you pass in.- Each anonymous function calls
Worker.work/1with a label. - The returned process IDs (PIDs) can be stored in variables, though this is optional. Here, we use variables prefixed with an underscore to avoid “unused variable” warnings. If you do not need to reference the process later, you can simply call
spawnwithout assigning the result. - These processes run concurrently and do not block the main process.
After spawning the workers, the main process continues immediately. We add a short sleep so the program does not exit before the workers finish.
Explanation:
- The main process prints a message right away.
Process.sleep(2000)keeps the main process alive for 2 seconds. Since each worker sleeps for 1 second, this gives them time to print “finished!” before the program ends.
You saw how to define a function, spawn multiple processes to run it concurrently, and keep the main process alive long enough to see their output. This pattern — define work, spawn processes, and manage timing — is the foundation for building concurrent systems in Elixir.
Ready to put this into action? Head to the practice section and try it yourself.
