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?
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 thereceive
expires, if any).receive
blocks until a matching message is available. You can easily check it withio:format()
ordbg
.spawn_link
orspawn_monitor
, otherwise the "children" thread may die and the "parent" will be waiting forever for a message that is't not going to come.