| 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
}
}
If the mutex is locked, unlocks the mutex, wakes one waiting thread, and yields in a critical section.
# File lib/thread.rb, line 145
145: def exclusive_unlock
146: return unless @locked
147: Thread.exclusive do
148: @locked = false
149: begin
150: t = @waiting.shift
151: t.wakeup if t
152: rescue ThreadError
153: retry
154: end
155: yield
156: end
157: self
158: end
Releases the lock. Returns nil if ref wasn‘t locked.
# File lib/thread.rb, line 110
110: def unlock
111: return unless @locked
112: Thread.critical = true
113: @locked = false
114: begin
115: t = @waiting.shift
116: t.wakeup if t
117: rescue ThreadError
118: retry
119: end
120: Thread.critical = false
121: begin
122: t.run if t
123: rescue ThreadError
124: end
125: self
126: end