Class: Concurrent::Exchanger

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

Overview

Note:

Edge Feature: Edge features are under active development and may change frequently. They are expected not to keep backward compatibility (there may also lack tests and documentation). Semantic versions will be obeyed though. Features developed in concurrent-ruby-edge are expected to move to concurrent-ruby when final.

A synchronization point at which threads can pair and swap elements within pairs. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return.

Uses MVar to manage synchronization of the individual elements. Since MVar is also a Dereferenceable, the exchanged values support all dereferenceable options. The constructor options hash will be passed to the MVar constructors.

Constant Summary collapse

EMPTY =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Exchanger

Create a new Exchanger object.

Parameters:

  • opts (Hash) (defaults to: {}) —

    the options controlling how the managed references will be processed



25
26
27
28
# File 'lib/concurrent/exchanger.rb', line 25

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

Instance Method Details

#exchange(value, timeout = nil) ⇒ Object

Waits for another thread to arrive at this exchange point (unless the current thread is interrupted), and then transfers the given object to it, receiving its object in return.

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



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/concurrent/exchanger.rb', line 38

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