]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/compat19.rb
greed: refactor and prepare for more complete play
[user/henk/code/ruby/rbot.git] / lib / rbot / compat19.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: ruby 1.9 compatibility (monkey)patches
5
6 require 'timeout'
7 require "thread"
8
9 class ConditionVariable
10
11   def wait(mutex, timeout=nil)
12     begin
13       # TODO: mutex should not be used
14       @waiters_mutex.synchronize do
15         @waiters.push(Thread.current)
16       end
17       if timeout
18         elapsed = mutex.sleep timeout if timeout > 0.0
19         unless timeout > 0.0 and elapsed < timeout
20           t = @waiters_mutex.synchronize { @waiters.delete Thread.current }
21           signal unless t # if we got notified, pass it along
22           raise TimeoutError, "wait timed out"
23         end
24       else
25         mutex.sleep
26       end
27     end
28     nil
29   end
30
31 end
32
33 require 'monitor'
34
35 module MonitorMixin
36
37   class ConditionVariable
38
39     def wait(timeout = nil)
40       #if timeout
41       #  raise NotImplementedError, "timeout is not implemented yet"
42       #end
43       @monitor.__send__(:mon_check_owner)
44       count = @monitor.__send__(:mon_exit_for_cond)
45       begin
46         @cond.wait(@monitor.instance_variable_get("@mon_mutex"), timeout)
47         return true
48       rescue TimeoutError
49         return false
50       ensure
51         @monitor.__send__(:mon_enter_for_cond, count)
52       end
53     end
54
55     def signal
56       @monitor.__send__(:mon_check_owner)
57       @cond.signal
58     end
59
60     def broadcast
61       @monitor.__send__(:mon_check_owner)
62       @cond.broadcast
63     end
64
65   end  # ConditionVariable
66
67   def self.extend_object(obj)
68     super(obj)
69     obj.__send__(:mon_initialize)
70   end
71
72 end # MonitorMixin