none
agents - receive first of? RRS feed

  • Question

  • How could I achieve a receive with a filter predicate which will take the first element which fulfills the predicate, that is it doesn't just check the head element as the usual receive does.

    I want to achieve the following:

    unbounded_buffer<int> buffer;
    
    send(buffer, 3);
    send(buffer, 2);
    send(buffer, 4);
    
    // The following will succeed, val == 2
    // I want to get the first value in the buffer which fulfills the predicate.
    int val = receive_first_of(buffer, [](int n){return n % 2 == 0;});
    
    // The following is the usual behavior which will block since the first element does not fulfill filter predicate.
    int val = receive(buffer, [](int n){return n % 2 == 0;});

    • Edited by Dragon89 Friday, October 21, 2011 10:21 AM
    Thursday, October 20, 2011 5:07 PM

Answers

  • Hello,

    Great question.

    Our unbounded buffer guarantees in-order delivery, which is important for most pipeline scenarios.

    To do what you want, and strictly following your example, which is to decide at the receive point what the predicate is, you would have to implement an unordered buffer yourself.

    That said, if the predicate is applied to all elements, simply link another buffer with the predicate first, then link a buffer that has no predicate. When propagating messages, the links are attempted in the order they are established. Thus, you require three buffers instead of one and it only works if the predicate isn’t transient.

    Thanks

    Rahul


    Rahul V. Patil
    Monday, October 31, 2011 11:11 PM
    Moderator

All replies

  • Hello,

    Great question.

    Our unbounded buffer guarantees in-order delivery, which is important for most pipeline scenarios.

    To do what you want, and strictly following your example, which is to decide at the receive point what the predicate is, you would have to implement an unordered buffer yourself.

    That said, if the predicate is applied to all elements, simply link another buffer with the predicate first, then link a buffer that has no predicate. When propagating messages, the links are attempted in the order they are established. Thus, you require three buffers instead of one and it only works if the predicate isn’t transient.

    Thanks

    Rahul


    Rahul V. Patil
    Monday, October 31, 2011 11:11 PM
    Moderator
  • I solved the problem for my specific problem by linking target buffers:

    unbounded_buffer<int> buffer;
    unbounded_buffer<int> even_numbers([](int n){return n % 2 == 0;});
    unbounded_buffer<int> everything_else;
    
    buffer.link_target(&even_numbers);
    buffer.link_target(&everything_else); 
    
    int val = receive(even_numbers);
    


    Wednesday, November 2, 2011 12:16 AM