Class: Concurrent::Exchanger

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/exchanger.rb

Constant Summary collapse

EMPTY =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Exchanger

Returns a new instance of Exchanger.



6
7
8
9
# File 'lib/concurrent/exchanger.rb', line 6

def initialize(opts = {})
  @first = MVar.new(EMPTY, opts)
  @second = MVar.new(MVar::EMPTY, opts)
end

Instance Method Details

#exchange(value, timeout = nil) ⇒ Object

Returns the value exchanged by the other thread; nil if timed out.

Parameters:

  • value (Object)

    the value to exchange with an other thread

  • timeout (Numeric) (defaults to: nil)

    the maximum time in second to wait for one other thread. nil (default value) means no timeout

Returns:

  • (Object)

    the value exchanged by the other thread; nil if timed out



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/concurrent/exchanger.rb', line 14

def exchange(value, timeout = nil)
  first = @first.take(timeout)
  if first == MVar::TIMEOUT
    nil
  elsif first == EMPTY
    @first.put value
    second = @second.take timeout
    if second == MVar::TIMEOUT
      nil
    else
      second
    end
  else
    @first.put EMPTY
    @second.put value
    first
  end
end