struct Atomic(T)

Overview

A value that may be updated atomically.

Only primitive integer types, reference types or nilable reference types can be used with an Atomic type.

Defined in:

atomic.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(value : T)Source

Creates an Atomic with the given initial value.

Instance Method Detail

def add(value : T) : TSource

Performs atomic_value += value. Returns the old value.

atomic = Atomic.new(1)
atomic.add(2) # => 1
atomic.get    # => 3

def and(value : T) : TSource

Performs atomic_value &= value. Returns the old value.

atomic = Atomic.new(5)
atomic.and(3) # => 5
atomic.get    # => 1

def compare_and_set(cmp : T, new : T) : Tuple(T, Bool)Source

Compares this atomic's value with cmp:

  • if they are equal, sets the value to new, and returns {old_value, true}
  • if they are not equal the value remains the same, and returns {old_value, false}
atomic = Atomic.new(1)

atomic.compare_and_set(2, 3) # => {1, false}
atomic.get                   # => 1

atomic.compare_and_set(1, 3) # => {1, true}
atomic.get                   # => 3

def get : TSource

Atomically returns this atomic's value.

def lazy_getSource

Non-atomically returns this atomic's value.

def lazy_set(value : T) : TSource

Non-atomically sets this atomic's value to value. Returns the new value.

atomic = Atomic.new(5)
atomic.lazy_set(10) # => 10
atomic.get          # => 10

def max(value : T)Source

Performs atomic_value = max(atomic_value, value). Returns the old value.

atomic = Atomic.new(5)

atomic.max(3) # => 5
atomic.get    # => 5

atomic.max(10) # => 5
atomic.get     # => 10

def min(value : T)Source

Performs atomic_value = min(atomic_value, value). Returns the old value.

atomic = Atomic.new(5)

atomic.min(10) # => 5
atomic.get     # => 5

atomic.min(3) # => 5
atomic.get    # => 3

def nand(value : T) : TSource

Performs atomic_value = ~(atomic_value & value). Returns the old value.

atomic = Atomic.new(5)
atomic.nand(3) # => 5
atomic.get     # => -2

def or(value : T) : TSource

Performs atomic_value |= value. Returns the old value.

atomic = Atomic.new(5)
atomic.or(2) # => 5
atomic.get   # => 7

def set(value : T) : TSource

Atomically sets this atomic's value to value. Returns the new value.

atomic = Atomic.new(5)
atomic.set(10) # => 10
atomic.get     # => 10

def sub(value : T) : TSource

Performs atomic_value -= value. Returns the old value.

atomic = Atomic.new(9)
atomic.sub(2) # => 9
atomic.get    # => 7

def swap(value : T)Source

Atomically sets this atomic's value to value. Returns the old value.

atomic = Atomic.new(5)
atomic.swap(10) # => 5
atomic.get      # => 10

def xor(value : T) : TSource

Performs atomic_value ^= value. Returns the old value.

atomic = Atomic.new(5)
atomic.xor(3) # => 5
atomic.get    # => 6

© 2012–2021 Manas Technology Solutions.
Licensed under the Apache License, Version 2.0.
https://crystal-lang.org/api/1.2.1/Atomic.html