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. As we explored, we discovered that message passing in the REPL is a little cumbersome. You were also promised that it would be cleaner when we moved the code to modules. Let's see if that's true ...
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!