Tutorial: Lightweight Processes

2 Processes in Modules

2.1 Shell spawn: The Sequel

In the last section, we were all primed to explore spawning processes from the REPL. Let's put the code from before into a module.

Save the code below to messenger.lfe:

(defmodule messenger
 (export (print-result 0)))

(defun print-result ()
  (receive
    (msg
      (: io format '"Received message: '~s'~n" (list msg)))))

Then start up lfe, compile your new module, and spawn our print function:

> (c '"messenger")
#(module messenger)
> (set pid (spawn 'messenger 'print-result ()))
<0.51.0>

Great! It works as expected. Now let's play... by sending it a message from the REPL:

> (! pid '"Zaphod was here.")
"Zaphod was here."
Received message: 'Zaphod was here.'

The only problem with our solution is that it's a one-shot deal; subsequent sends to the pid won't call our function, since that function is no longer running. We can change that, though: let's make sure that once it prints the message, it starts listening again:

(defmodule messenger
 (export (print-result 0)))

(defun print-result ()
  (receive
    (msg
      (: io format '"Received message: '~s'~n" (list msg))
      (print-result))))

Let's take it for a test drive:

> (c '"messenger")
#(module messenger)
> (set pid (spawn 'messenger 'print-result ()))
<0.55.0>
> (! pid '"Zaphod was here.")
"Zaphod was here."
Received message: 'Zaphod was here.'
> (! pid '"Ford is missing.")
"Ford is missing."
Received message: 'Ford is missing.'
> (! pid '"Arthur is pining for Trillian.")
"Arthur is pining for Trillian."
Received message: 'Arthur is pining for Trillian.'

Horray! You've just written a simple listener in LFE!