class ActiveSupport::Concurrency::ShareLock
Разделяемая/эксклюзивная блокировка, также известная как блокировка чтения-записи.
Открытые методы класса
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 49
def initialize
super()
@cv = new_cond
@sharing = Hash.new(0)
@waiting = {}
@sleeping = {}
@exclusive_thread = nil
@exclusive_depth = 0
end Открытые методы экземпляра
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 147
def exclusive(purpose: nil, compatible: [], after_compatible: [], no_wait: false)
if start_exclusive(purpose: purpose, compatible: compatible, no_wait: no_wait)
begin
yield
ensure
stop_exclusive(compatible: after_compatible)
end
end
end Выполняет переданный блок, удерживая эксклюзивную блокировку. Если задано no_wait и блокировка недоступна немедленно, возвращает nil, не вызывая блок. В противном случае возвращает результат выполнения блока.
Другие параметры см. в описании start_exclusive.
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 158
def sharing
start_sharing
begin
yield
ensure
stop_sharing
end
end Выполняет переданный блок, удерживая разделяемую блокировку.
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 75
def start_exclusive(purpose: nil, compatible: [], no_wait: false)
synchronize do
unless @exclusive_thread == Thread.current
if busy_for_exclusive?(purpose)
return false if no_wait
yield_shares(purpose: purpose, compatible: compatible, block_share: true) do
wait_for(:start_exclusive) { busy_for_exclusive?(purpose) }
end
end
@exclusive_thread = Thread.current
end
@exclusive_depth += 1
true
end
end Возвращает false, если задано no_wait и блокировка недоступна немедленно. В противном случае возвращает true после получения блокировки.
Параметры purpose и compatible работают совместно: пока этот поток ожидает эксклюзивную блокировку, он уступает свою разделяемую блокировку (если она есть) любой другой попытке, значение purpose которой присутствует в списке compatible этой попытки. Это позволяет выполнить «нестрогое» повышение уровня блокировки, которое за счёт меньшей строгости предотвращает некоторые виды взаимных блокировок.
Для многих ресурсов достаточно нестрогого повышения уровня блокировки: если поток ожидает блокировку, он не выполняет никакой другой код. При совпадении purpose можно уступать блокировку только другим потокам, действия которых не будут мешать.
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 113
def start_sharing
synchronize do
if @sharing[Thread.current] > 0 || @exclusive_thread == Thread.current
# We already hold a lock; nothing to wait for
elsif @waiting[Thread.current]
# We're nested inside a +yield_shares+ call: we'll resume as
# soon as there isn't an exclusive lock in our way
wait_for(:start_sharing) { @exclusive_thread }
else
# This is an initial / outermost share call: any outstanding
# requests for an exclusive lock get to go first
wait_for(:start_sharing) { busy_for_sharing?(false) }
end
@sharing[Thread.current] += 1
end
end # File activesupport/lib/active_support/concurrency/share_lock.rb, line 95
def stop_exclusive(compatible: [])
synchronize do
raise "invalid unlock" if @exclusive_thread != Thread.current
@exclusive_depth -= 1
if @exclusive_depth == 0
@exclusive_thread = nil
if eligible_waiters?(compatible)
yield_shares(compatible: compatible, block_share: true) do
wait_for(:stop_exclusive) { @exclusive_thread || eligible_waiters?(compatible) }
end
end
@cv.broadcast
end
end
end Освобождает эксклюзивную блокировку. Вызывать этот метод может только поток, вызвавший start_exclusive (и удерживающий блокировку в данный момент).
# File activesupport/lib/active_support/concurrency/share_lock.rb, line 130
def stop_sharing
synchronize do
if @sharing[Thread.current] > 1
@sharing[Thread.current] -= 1
else
@sharing.delete Thread.current
@cv.broadcast
end
end
end Временно освобождает все удерживаемые разделяемые блокировки на время выполнения переданного блока, позволяя выполнить любой запрос на эксклюзивную блокировку compatible.
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.