Empty Process Mail box in Erlang
Asked Answered
L

1

5

when you send a message to the shell process, you can flush all messages out by calling: c:flush().

C:\Windows\System32>erl
Eshell V5.9  (abort with ^G)
1> self() ! josh.
josh
2> self() ! me.
me
3> self() ! you.
you
4> flush().
Shell got josh
Shell got me
Shell got you
ok
5>

In my thinking , this empties the mail box of the shell process. What is the equivalent way of emptying the mailbox of any erlang process ?

Loar answered 16/8, 2012 at 14:39 Comment(0)
M
9

This function should flush all messages from mailbox (in any process where you call it):

flush() ->
        receive
                _ -> flush()
        after
                0 -> ok
        end.
Mandie answered 16/8, 2012 at 14:54 Comment(3)
Thanks @stemm. I am wondering: after 0 -> ok doesn't it force the process out of the receive immediately ? what is your reference for this, please ?Loar
As I understood (and checked in practice) this function would receive all existing messages, while mailbox is not empty. I've read this tip in Francesco Cesarini book Erlang Programming (in 4th paragraph - about parallell programming)Mandie
Yes, the after 0 -> is guaranteed to try and match through all the messages in the mailbox before it "times out". It is more efficient than doing after 1 -> as no timer will actually be started; it is not needed.Cubicle

© 2022 - 2024 — McMap. All rights reserved.