mootoh (owner)

Revisions

gist: 166928 Download_button fork
public
Public Clone URL: git://gist.github.com/166928.git
Embed All Files: show embed
stm.rb #
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# A Software Transactional Memory implementation.
#
# from Beautiful Code Chapter 24.
#
# mootoh (mootoh@gmail.com)
#
 
module STM
   $global_mutex = Mutex.new
 
   class TVar
      attr_accessor :shared_value
 
      def initialize(x=0)
         Thread.current[:stm_log] ||= {}
 
         @shared_value = x
         Thread.current[:stm_log][self] = []
      end
 
      def read
         if Thread.current[:stm_log][self].empty?
            Thread.current[:stm_log][self].push @shared_value
         end
 
         Thread.current[:stm_log][self].last
      end
 
      def write(value)
         Thread.current[:stm_log][self].push value
      end
   end # TVar
 
   # action
   def atomically
      Thread.current[:stm_log] ||= {}
 
      yield
 
      $global_mutex.synchronize {
         validate
         commit
      }
   end
 
   def retry
   end
 
   def orElse
   end
 
   # TODO: should check related transactions only
   def validate
      Thread.current[:stm_log].each do |tvar, log|
         if log.first != tvar.shared_value
            # abort the transaction
            raise 'inconsist transaction'
         end
      end
   end
 
   # TODO: should commit related transactions only
   def commit
      Thread.current[:stm_log].each do |tvar, log|
         log.each do |value|
            tvar.shared_value = value
         end
         log.clear
      end
   end
 
   module_function :atomically
   module_function :retry
   module_function :orElse
   module_function :validate
   module_function :commit
 
end # STM