adi solo
adi solo

Reputation: 55

Process message prioritizing Erlang, also known as Selective Receives

I have a process code, and i want to send a 'die' question to kill it. But i want to make sure that every time the kill message is prioritized, so if there is one - the process will die immediately.

receive 
 die -> dead;
after
0 -> receive
      Message -> do_something(Message)
    after
    0 -> func(NewX)
    end
end.

Upvotes: 2

Views: 68

Answers (1)

José M
José M

Reputation: 3509

With your code, you're busy-waiting, you can do something like:

func(X) ->
    receive % This checks the whole mailbox for 'die'
        die -> dead; 
    after 0 -> % No 'die' message in mailbox, process the next Message whenever it arrives
        receive % This checks only the next Message in the mailbox
            die -> dead;
            Message -> func(do_something(X, Message))
        end
    end.

Upvotes: 3

Related Questions