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

Methods

Public Class methods

Creates a new Mutex

[Source]

    # File lib/thread.rb, line 60
60:   def initialize
61:     @waiting = []
62:     @locked = false;
63:     @waiting.taint              # enable tainted comunication
64:     self.taint
65:   end

Public Instance methods

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

[Source]

     # 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

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

[Source]

     # File lib/thread.rb, line 92
 92:   def lock
 93:     while (Thread.critical = true; @locked)
 94:       @waiting.push Thread.current
 95:       Thread.stop
 96:     end
 97:     @locked = true
 98:     Thread.critical = false
 99:     self
100:   end

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

[Source]

    # File lib/thread.rb, line 70
70:   def locked?
71:     @locked
72:   end

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

[Source]

     # File lib/thread.rb, line 127
127:   def synchronize
128:     lock
129:     begin
130:       yield
131:     ensure
132:       unlock
133:     end
134:   end

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

[Source]

    # File lib/thread.rb, line 78
78:   def try_lock
79:     result = false
80:     Thread.critical = true
81:     unless @locked
82:       @locked = true
83:       result = true
84:     end
85:     Thread.critical = false
86:     result
87:   end

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

[Source]

     # 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

[Validate]