File: safe_monitor.rb

package info (click to toggle)
ruby-ref 1.0.5%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 332 kB
  • ctags: 186
  • sloc: ruby: 1,107; java: 92; makefile: 2
file content (50 lines) | stat: -rw-r--r-- 1,054 bytes parent folder | download
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
begin
  require 'thread'
rescue LoadError
  # Threads not available. Monitor will do nothing.
end

module Ref
  # The Monitor class in Ruby 1.8 has some bugs and also threads may not be available on all
  # runtimes. This class provides a simple, safe re-entrant mutex as an alternative.
  class SafeMonitor
    def initialize
      @owner = nil
      @count = 0
      @mutex = defined?(Mutex) ? Mutex.new : nil
    end
  
    # Acquire an exclusive lock.
    def lock
      if @mutex
        if @owner != Thread.current.object_id
          @mutex.lock
          @owner = Thread.current.object_id
        end
        @count += 1
      end
      true
    end
    
    # Release the exclusive lock.
    def unlock
      if @mutex
        if @owner == Thread.current.object_id
          @count -= 1
          if @count == 0
            @owner = nil
            @mutex.unlock
          end
        end
      end
    end
  
    # Run a block of code with an exclusive lock.
    def synchronize
      lock
      yield
    ensure
      unlock
    end
  end
end