Erlang: getting statement with multiple timeout clauses

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

I want to do something like

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

      

where, whichever is Timeout1

or Timeout2

less, is called doSomething1()

or doSomething2

. However, the above code throws a syntax error.

If, as I am beginning to suspect, this is not possible, what is the best way to achieve the same result in a suitable Erlangi manner?

Thanks in advance!

+2


source to share


2 answers


No, you cannot. Just decide what to do before you receive it.

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

      

or



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

      

and etc.

+4


source


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



0


source







All Articles