| 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
Attempts to grab the lock and waits if it isn’t available.
# File lib/thread.rb, line 97
97: def lock
98: while (Thread.critical = true; @locked)
99: @waiting.push Thread.current
100: Thread.stop
101: end
102: @locked = true
103: Thread.critical = false
104: self
105: end
Returns true if this lock is currently held by some thread.
# File lib/thread.rb, line 75
75: def locked?
76: @locked
77: end
Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.
# File lib/thread.rb, line 83
83: def try_lock
84: result = false
85: Thread.critical = true
86: unless @locked
87: @locked = true
88: result = true
89: end
90: Thread.critical = false
91: result
92: 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