File: volatile_tuple.rb

package info (click to toggle)
ruby-thread-safe 0.3.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 712 kB
  • sloc: java: 5,458; ruby: 2,917; makefile: 6
file content (46 lines) | stat: -rw-r--r-- 1,029 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module ThreadSafe
  module Util
    # A fixed size array with volatile volatile getters/setters.
    # Usage:
    #   arr = VolatileTuple.new(16)
    #   arr.volatile_set(0, :foo)
    #   arr.volatile_get(0)    # => :foo
    #   arr.cas(0, :foo, :bar) # => true
    #   arr.volatile_get(0)    # => :bar
    class VolatileTuple
      include Enumerable

      Tuple = defined?(Rubinius::Tuple) ? Rubinius::Tuple : Array

      def initialize(size)
        @tuple = tuple = Tuple.new(size)
        i = 0
        while i < size
          tuple[i] = AtomicReference.new
          i += 1
        end
      end

      def volatile_get(i)
        @tuple[i].get
      end

      def volatile_set(i, value)
        @tuple[i].set(value)
      end

      def compare_and_set(i, old_value, new_value)
        @tuple[i].compare_and_set(old_value, new_value)
      end
      alias_method :cas, :compare_and_set

      def size
        @tuple.size
      end

      def each
        @tuple.each {|ref| yield ref.get}
      end
    end
  end
end