| 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 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
Releases the lock. Returns nil if ref wasn‘t locked.
# File lib/thread.rb, line 105
105: def unlock
106: return unless @locked
107: Thread.critical = true
108: @locked = false
109: begin
110: t = @waiting.shift
111: t.wakeup if t
112: rescue ThreadError
113: retry
114: end
115: Thread.critical = false
116: begin
117: t.run if t
118: rescue ThreadError
119: end
120: self
121: end