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 65
65:   def initialize
66:     @waiting = []
67:     @locked = false;
68:     @waiting.taint              # enable tainted comunication
69:     self.taint
70:   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 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.

[Source]

     # 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.

[Source]

    # File lib/thread.rb, line 75
75:   def locked?
76:     @locked
77:   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 132
132:   def synchronize
133:     lock
134:     begin
135:       yield
136:     ensure
137:       unlock
138:     end
139:   end

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

[Source]

    # 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.

[Source]

     # 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

[Validate]