Method: Concurrent::ReadWriteLock#acquire_read_lock

Defined in:
lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb

#acquire_read_lockBoolean

Acquire a read lock. If a write lock has been acquired will block until it is released. Will not block if other read locks have been acquired.

Returns:

  • (Boolean)

    true if the lock is successfully acquired

Raises:



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb', line 111

def acquire_read_lock
  while true
    c = @Counter.value
    raise ResourceLimitError.new('Too many reader threads') if max_readers?(c)

    # If a writer is waiting when we first queue up, we need to wait
    if waiting_writer?(c)
      @ReadLock.wait_until { !waiting_writer? }

      # after a reader has waited once, they are allowed to "barge" ahead of waiting writers
      # but if a writer is *running*, the reader still needs to wait (naturally)
      while true
        c = @Counter.value
        if running_writer?(c)
          @ReadLock.wait_until { !running_writer? }
        else
          return if @Counter.compare_and_set(c, c+1)
        end
      end
    else
      break if @Counter.compare_and_set(c, c+1)
    end
  end
  true
end