Class: BreakingMutex

Inherits:
Object
  • Object
show all
Defined in:
lib/appswarm/breaking_mutex.rb

Overview

BreakingMutex=Mutex

Constant Summary collapse

GRANULARITY =
20
TRIES =
10

Instance Method Summary collapse

Constructor Details

#initialize(timeout = 2) ⇒ BreakingMutex

Returns a new instance of BreakingMutex.



5
6
7
8
9
# File 'lib/appswarm/breaking_mutex.rb', line 5

def initialize(timeout=2)
  @timeout=timeout
  #@mutex=Mutex.new
  @mutex=false
end

Instance Method Details

#synchronize(&b) ⇒ Object



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
# File 'lib/appswarm/breaking_mutex.rb', line 10

def synchronize(&b)
  done=false
  start=Time.now
  while not done and (Time.now-start)<@timeout
    puts "enter critical"
    Thread.critical=true
      ok=false
      if @mutex==false
        @mutex=true
        ok=true
      end
    puts "leaving critical"
    Thread.critical=false
      if ok==true
        puts "running"
        b.call
        done=true
      end
    if ok==true
      puts "enter critical"
      Thread.critical=true
        @mutex=false
      Thread.critical=false
      puts "leaving critical"
    end
    time=(@timeout/TRIES.to_f)*rand(GRANULARITY)/GRANULARITY.to_f
    puts "SLEEP #{time}"
    sleep time unless done
  end
  puts "DONE"
end