class Ractor::TMVar

TMVar for Ractor inspired by Haskell's TMVar based on Ractor::TVar.

Constants

EMPTY

represents “empty” value for TMVar

VERSION

Public Class Methods

new(value = nil) click to toggle source

initialize TMVar

@param [Object] value Value to set TVar. It needs to be shareable.

@return [TMVar]

# File lib/ractor/tmvar.rb, line 20
def initialize(value = nil)
  @tvar = Ractor::TVar.new(value)
end

Public Instance Methods

empty?() click to toggle source

return the value is “empty” or not.

@param [Boolean]

# File lib/ractor/tmvar.rb, line 109
def empty?
  @tvar.value == EMPTY
end
put(new_value) click to toggle source

write the given value. If the current value is not “empty”, it retries the transaction.

@param [Object] new_value neet to be shareable

# File lib/ractor/tmvar.rb, line 84
def put(new_value)
  raise Ractor::RetryTransaction if @tvar.value != EMPTY

  @tvar.value = new_value
end
read() click to toggle source

get the value like take. The difference between take and read is take leaves the value blank, but read not change the value to blank.

@return [Object] value of internal TVar.

# File lib/ractor/tmvar.rb, line 61
def read
  v = @tvar.value
  raise Ractor::RetryTransaction if v == EMPTY

  v
end
swap(new) click to toggle source

get the the value like get, and replace the value to the given value if the current value is not “empty”

@param [Object] new_value neet to be shareable

# File lib/ractor/tmvar.rb, line 118
def swap(new)
  v = @tvar.value
  raise Ractor::RetryTransaction if v == EMPTY

  @tvar.value = new
  v
end
take() click to toggle source

get the value and leave the value to “empty” If the value is already “empty”, it will retry the transaction. @note You need to wrap it by Ractor.atomically even if you only call take

because +TVar#value=+ needs atomically.

@return [Object] value of internal TVar.

# File lib/ractor/tmvar.rb, line 32
def take
  v = @tvar.value
  raise Ractor::RetryTransaction if v == EMPTY

  @tvar.value = EMPTY
  v
end
try_put(new_value) click to toggle source

try to put value to TVar's value If the value is not “empty”, it will not retry and only return false. If it succeed to put, it returns true.

@param [Object] new_value neet to be shareable

# File lib/ractor/tmvar.rb, line 97
def try_put(new_value)
  return false if @tvar.value != EMPTY

  @tvar.value = new_value
  true
end
try_read() click to toggle source

read the value like read but it does not retry.

@return [Object] value of internal TVar.

# File lib/ractor/tmvar.rb, line 73
def try_read
  v = @tvar.value
  v == EMPTY ? nil : v
end
try_take() click to toggle source

try to get the value. If the value is “empty”, it returns nil.

@return [Object] value of internal TVar, only if exists.

# File lib/ractor/tmvar.rb, line 46
def try_take
  v = @tvar.value
  return nil if v == EMPTY

  @tvar.value = EMPTY
  v
end