In Files

  • thread.rb

Class/Module Index [+]

Quicksearch

Mutex

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
  }
}

Public Class Methods

new() click to toggle source

Creates a new Mutex

 
               # File thread.rb, line 60
def initialize
  @waiting = []
  @locked = false;
  @waiting.taint              # enable tainted comunication
  self.taint
end
            

Public Instance Methods

exclusive_unlock() click to toggle source

If the mutex is locked, unlocks the mutex, wakes one waiting thread, and yields in a critical section.

 
               # File thread.rb, line 140
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
            
lock() click to toggle source

Attempts to grab the lock and waits if it isn't available.

 
               # File thread.rb, line 92
def lock
  while (Thread.critical = true; @locked)
    @waiting.push Thread.current
    Thread.stop
  end
  @locked = true
  Thread.critical = false
  self
end
            
locked?() click to toggle source

Returns true if this lock is currently held by some thread.

 
               # File thread.rb, line 70
def locked?
  @locked
end
            
synchronize() click to toggle source

Obtains a lock, runs the block, and releases the lock when the block completes. See the example under Mutex.

 
               # File thread.rb, line 127
def synchronize
  lock
  begin
    yield
  ensure
    unlock
  end
end
            
try_lock() click to toggle source

Attempts to obtain the lock and returns immediately. Returns true if the lock was granted.

 
               # File thread.rb, line 78
def try_lock
  result = false
  Thread.critical = true
  unless @locked
    @locked = true
    result = true
  end
  Thread.critical = false
  result
end
            
unlock() click to toggle source

Releases the lock. Returns nil if ref wasn't locked.

 
               # File thread.rb, line 105
def unlock
  return unless @locked
  Thread.critical = true
  @locked = false
  begin
    t = @waiting.shift
    t.wakeup if t
  rescue ThreadError
    retry
  end
  Thread.critical = false
  begin
    t.run if t
  rescue ThreadError
  end
  self
end