Class: Farce::Concurrent::Tuple

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Shareable::Delegated
Defined in:
lib/farce/concurrent/tuple.rb

Overview

A replacement for Concurrent::Tuple from concurrent-ruby.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Shareable

#ractor_shareable?

Constructor Details

#initialize(size) ⇒ Tuple

Returns a new instance of Tuple.

Parameters:

  • size (Integer) —

    the size of the tuple



17
18
19
20
21
# File 'lib/farce/concurrent/tuple.rb', line 17

def initialize(size)
  @size  = Integer(size)
  @tuple = Vector.new(@size)
  super()
end

Instance Attribute Details

#size ⇒ Integer (readonly)

Returns the size of the tuple.

Returns:

  • (Integer) —

    the size of the tuple



14
15
16
# File 'lib/farce/concurrent/tuple.rb', line 14

def size
  @size
end

Instance Method Details

#compare_and_set(index, old_value, new_value) ⇒ Boolean Also known as: cas

Atomically sets the value at the given index to new_value if the current value is equal to old_value.

Parameters:

  • index (Integer) —

    the index of the value to set

  • old_value (BasicObject) —

    the expected current value

  • new_value (BasicObject) —

    the new value to set

Returns:

  • (Boolean) —

    true if the value was set, false otherwise



41
42
43
44
# File 'lib/farce/concurrent/tuple.rb', line 41

def compare_and_set(index, old_value, new_value)
  return false unless index.between?(0, @size - 1)
  @tuple.compare_and_set(index, old_value, new_value)
end

#each {|value| ... } ⇒ Enumerator, self

Iterates over each element in the tuple.

Yield Parameters:

  • value (BasicObject) —

    the value of each element

Returns:

  • (Enumerator, self) —

    if no block is given, self otherwise



50
51
52
53
54
# File 'lib/farce/concurrent/tuple.rb', line 50

def each(&)
  return enum_for(:each) unless block_given?
  @tuple.each(&)
  self
end

#get(index) ⇒ BasicObject? Also known as: volatile_get

Retrieves the value at the given index, or nil if the index is out of bounds.

Parameters:

  • index (Integer) —

    the index of the value to retrieve

Returns:

  • (BasicObject, nil) —

    the value at the given index, or nil if out of bounds



26
# File 'lib/farce/concurrent/tuple.rb', line 26

def get(index) = index.between?(0, @size - 1) ? @tuple[index] : nil

#set(index, value) ⇒ BasicObject? Also known as: volatile_set

Sets the value at the given index, or does nothing if the index is out of bounds.

Parameters:

  • index (Integer) —

    the index of the value to set

  • value (BasicObject) —

    the value to set

Returns:

  • (BasicObject, nil) —

    the value set, or nil if out of bounds



33
# File 'lib/farce/concurrent/tuple.rb', line 33

def set(index, value) = index.between?(0, @size - 1) ? @tuple[index] = value : nil