Class | Mutex |
In: |
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 thread.rb, line 145 def exclusive_unlock return unless @locked Thread.exclusive do @locked = false begin t = @waiting.shift t.wakeup if t rescue ThreadError retry end yield end self end
Attempts to grab the lock and waits if it isn’t available.
# File thread.rb, line 97 def lock while (Thread.critical = true; @locked) @waiting.push Thread.current Thread.stop end @locked = true Thread.critical = false self end
Returns true if this lock is currently held by some thread.
# File thread.rb, line 75 def locked? @locked end
Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.
# File thread.rb, line 83 def try_lock result = false Thread.critical = true unless @locked @locked = true result = true end Thread.critical = false result end