tags:

views:

228

answers:

2

Is it possible for a receive statement to have multiple timeout clauses, and if so, what is the correct syntax?

I want to do something like

foo(Timout1, Timeout2) ->
    receive
    after
        Timeout1 ->
            doSomething1();
        Timeout2 ->
            doSomething2()
    end.

where, depending on which of Timeout1 or Timeout2 is smaller, doSomething1() or doSomething2 is called. However, the above code causes a syntax error.

If, as I'm beginning to suspect, this is not possible, what is the best way to achieve the same outcome in a suitable Erlangy manner?

Thanks in advance!

+3  A: 

No, you can't. Just decide what to do before receive.

foo(Timout1, Timeout2) ->
    {Timeout, ToDo} = if Timeout1 < Timeout2 -> {Timout1, fun doSomething1/0};
                         true -> {Timeout2, fun doSomething2/0} end,
    receive
    after Timeout -> ToDo()
    end.

or

foo(Timout1, Timeout2) when Timeout1 < Timeout2 ->
    receive
    after Timeout1 -> doSomething1()
    end;
foo(_, Timeout2) ->
    receive
    after Timeout2 -> doSomething2()
    end.

etc.

Hynek -Pichi- Vychodil
Thanks a lot. Any idea why Erlang lacks multiple timeout clauses? To me they would seem to make the code cleaner and easier to read.
grifaton
A: 

You should probably use a combination of 'gen_fsm' and 'timer:send_after'.

jldupont