Class: Splib::Monitor

Inherits:
Object
  • Object
show all
Defined in:
lib/splib/Monitor.rb

Instance Method Summary collapse

Constructor Details

#initializeMonitor

Returns a new instance of Monitor.



6
7
8
9
10
11
# File 'lib/splib/Monitor.rb', line 6

def initialize
    @threads = []
    @locks = []
    @lock_owner = nil
    @timers = {}
end

Instance Method Details

#broadcastObject

Wake up all threads



58
59
60
61
62
63
64
65
# File 'lib/splib/Monitor.rb', line 58

def broadcast
    synchronize do
        @threads.each do |t|
            t.wakeup if t.alive?
        end
        @threads.clear
    end
end

#lockObject

Lock the monitor



71
72
73
74
75
76
77
# File 'lib/splib/Monitor.rb', line 71

def lock
    if(Thread.exclusive{do_lock})
        until(owner?(Thread.current)) do
            Thread.stop
        end
    end
end

#locked?Boolean

Is monitor locked

Returns:

  • (Boolean)


83
84
85
# File 'lib/splib/Monitor.rb', line 83

def locked?
    @locks.size > 0
end

#signalObject

Wake up earliest thread



51
52
53
54
55
56
# File 'lib/splib/Monitor.rb', line 51

def signal
    synchronize do
        t = @threads.shift
        t.wakeup if t && t.alive?
    end
end

#synchronizeObject

Lock the monitor, execute block and unlock the monitor



87
88
89
90
91
92
93
94
95
# File 'lib/splib/Monitor.rb', line 87

def synchronize
    result = nil
    Thread.exclusive do
        do_lock
        result = yield
        do_unlock
    end
    result
end

#unlockObject

Unlock the monitor



79
80
81
# File 'lib/splib/Monitor.rb', line 79

def unlock
    Thread.exclusive{ do_unlock }
end

#wait(timeout = nil) ⇒ Object

timeout

Wait for given amount of time

Park a thread here



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/splib/Monitor.rb', line 14

def wait(timeout=nil)
    if(timeout)
        timout = timeout.to_f
        @timers[Thread.current] = Thread.new(Thread.current) do |t|
            time = 0.0
            until(time >= timeout) do
                s = Time.now.to_f
                sleep(timeout - time)
                time += Time.now.to_f - s
            end
            t.wakeup
        end
    end
    @threads << Thread.current
    Thread.stop
    @threads.delete(Thread.current)
    if(timeout)
        if(@timers[Thread.current].alive?)
            @timers[Thread.current].kill
        end
        @timers.delete(Thread.current)
    end
    true
end

#wait_untilObject

Park thread until block is true



45
46
47
48
49
# File 'lib/splib/Monitor.rb', line 45

def wait_until
    until yield
        wait
    end
end

#wait_whileObject

Park thread while block is true



39
40
41
42
43
# File 'lib/splib/Monitor.rb', line 39

def wait_while
    while yield
        wait
    end
end

#waitersObject

Number of threads waiting



67
68
69
# File 'lib/splib/Monitor.rb', line 67

def waiters
    @threads.size
end