Spawning Processes: What You’ll Learn

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.

Defining Work to Run in a Process

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/1 is 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.
Spawning Multiple Processes

Now we launch three processes, each running the worker function with a different name.

Explanation:

  • spawn starts a new, separate process that runs the anonymous function you pass in.
  • Each anonymous function calls Worker.work/1 with 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 spawn without assigning the result.
  • These processes run concurrently and do not block the main process.
Keeping the Main Process Alive

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.
Summary and Next Steps

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal