Is polling a receive-block in erlang good practice?

129 views Asked by At

I'm new to Erlang and have a question about the receive block. I'm trying to receive one or more message(s) from a child process that is performing a task. The way I found out how to receive a message is by using a receive-block.

E.g.

main() ->
    spawn(module, performSomething, []),
    receiveSomething().

receiveSomething() ->
    receive
        Var -> handleIt
    end,
    receiveSomething(). 

Question 1: Assuming the child may send multiple messages to the parent that needs to handle the messages, is 'polling' this receive block good practice? E.g. is this how it should be managed?

Question 2: It feels like it is some sort of busy wait, is it? E.g. does it cause a performance issue?

Question 3: In Objective-C, I would use delegates to receive callbacks and avoid polling. Are there alternatives in Erlang?

1

There are 1 answers

0
José M On BEST ANSWER
  1. Yes, it should be done that way. It's not polling: When executing the receive, the thread scans its mailbox for some message that matches, if it's found, it continues, if the message isn't found, the scheduler (os thread running the VM) suspends the execution of the thread until a matching message is available (or the timeout provided to the receive expires, if any).
  2. No, it's not a busy wait because the receive blocks until a matching message is available. You can easily check it with io:format() or dbg.
  3. That's what you're doing here, the "parent" thread spawns some other threads to perform some task and report back. The "parent" thread just waits for all the tasks to be completed.
  4. You should use spawn_link or spawn_monitor, otherwise the "children" thread may die and the "parent" will be waiting forever for a message that is't not going to come.