| Class | Mutex |
| In: |
lib/thread.rb
|
| Parent: | Object |
Mutex implements a simple semaphore that can be used to coordinate access to shared data from multiple concurrent threads.
Example:
require 'thread'
semaphore = Mutex.new
a = Thread.new {
semaphore.synchronize {
# access shared resource
}
}
b = Thread.new {
semaphore.synchronize {
# access shared resource
}
}
# File lib/thread.rb, line 61
61: def initialize
62: @waiting = []
63: @locked = false;
64: @waiting.taint # enable tainted comunication
65: self.taint
66: end
FIXME: not documented in Pickaxe/Nutshell.
# File lib/thread.rb, line 140
140: def exclusive_unlock
141: return unless @locked
142: Thread.exclusive do
143: @locked = false
144: begin
145: t = @waiting.shift
146: t.wakeup if t
147: rescue ThreadError
148: retry
149: end
150: yield
151: end
152: self
153: end
Attempts to grab the lock and waits if it isn’t available.
# File lib/thread.rb, line 93
93: def lock
94: while (Thread.critical = true; @locked)
95: @waiting.push Thread.current
96: Thread.stop
97: end
98: @locked = true
99: Thread.critical = false
100: self
101: end
Returns true if this lock is currently held by some thread.
# File lib/thread.rb, line 71
71: def locked?
72: @locked
73: end
Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.
# File lib/thread.rb, line 79
79: def try_lock
80: result = false
81: Thread.critical = true
82: unless @locked
83: @locked = true
84: result = true
85: end
86: Thread.critical = false
87: result
88: end
Releases the lock. Returns nil if ref wasn’t locked.
# File lib/thread.rb, line 106
106: def unlock
107: return unless @locked
108: Thread.critical = true
109: @locked = false
110: begin
111: t = @waiting.shift
112: t.wakeup if t
113: rescue ThreadError
114: retry
115: end
116: Thread.critical = false
117: begin
118: t.run if t
119: rescue ThreadError
120: end
121: self
122: end