O'Reilly logo

Programming Elixir 1.2 by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Simple Process

Here’s a module that defines a function we’d like to run as a separate process.

 defmodule​ SpawnBasic ​do
 def​ greet ​do
  IO.puts ​"​​Hello"
 end
 end

Yup, that’s it. There’s nothing special—it’s just regular code.

Let’s fire up iex and play:

 iex>​ c(​"​​spawn-basic.ex"​)
 [SpawnBasic]

First let’s call it as a regular function:

 iex>​ SpawnBasic.greet
 Hello
 :ok

Now let’s run it in a separate process:

 iex>​ spawn(SpawnBasic, ​:greet​, [])
 Hello
 #PID<0.42.0>

The spawn function kicks off a new process. It comes in many forms, but the two simplest ones let you run an anonymous function and run a named function in a module, passing a list of arguments. (We used the latter here.)

The spawn ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required