[erlang-questions] Effectiveness of "selective receive"

Ulf Wiger ulf@REDACTED
Fri Jul 31 19:05:26 CEST 2015

If I understand you correctly, you would essentially busy-loop over the ETS table until the object is gone? This would not be constant time.

Selective receive can be done largely in constant time if you take care, e.g.

call(Pid, Req) ->
   Ref = erlang:monitor(process, Pid),
   Pid ! {‘$call’, {self(), Ref}, Req},
      {Ref, Reply} -> Reply;
      {‘DOWN’, Ref, _, _, Reason} -> error(Reason)

The above will be detected by the compiler as an optimizable construct, since all patterns in the receive clause contain the newly created unique reference Ref. Therefore, the compiler can ‘mark’ the end of the message queue before creating Ref, then jump directly to the mark for the receive. No messages before the mark can contain Ref, since it didn’t exist then.

This optimization is built into gen_server:call(), but you can exploit it yourself by ensuring that the Ref creation (either monitor() or make_ref()) is done in the same scope (same function) as the receive, and the patterns in the receive clause all contain Ref.

The cost of the receive would be proportional to the number of messages arriving to the receiving process while it’s waiting, since it has to pattern-match on each.


> On 31 Jul 2015, at 17:13, Avinash Dhumane <nistrigunya@REDACTED <mailto:nistrigunya@REDACTED>> wrote:
> I have a need to lookup a tuple based on a 32-bit integer key and remove it from a set after it is found. The set is shared by 2 processes - one inserts the tuple and the other performs a lookup followed by a delete.
> So, I am considering ETS versus selective receive. Consideration for selective receive because I need the lookup call to block until the tuple becomes available in the set.
> I suppose selective receive will not be able to lookup in constant time whereas set-ETS will! But, I favour the selective receive because it makes the code so simple and intuitive. 
> So, my question is this - till what point, in terms of number of tuples in the set, the selective receive will be effective. The insertion in the set is capped at 400 tuples per second, but the lookup (followed by a delete) will be considerably slower (by 20 to 70%) than the rate of inserts.
> Please advise on considerations that apply in this situation in order to employ a suitable scheme.
> Thanks
> Avinash
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED <mailto:erlang-questions@REDACTED>
> http://erlang.org/mailman/listinfo/erlang-questions

Ulf Wiger, Co-founder & Developer Advocate, Feuerlabs Inc.
http://feuerlabs.com <http://feuerlabs.com/>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150731/ad0cd802/attachment.htm>

More information about the erlang-questions mailing list