أبسط تدفق: الاتصال بالخادم، حجز قفل واحد، ثم إعادته فورًا.
broker = Broker.connect(addr)
begin
broker.wait_ready(5)
ticket = broker.acquire("key", wait: 5, lease: 30)
ticket.release
puts "pass"
ensure
broker.close
endمثال يتحقق من أنه حتى مع عدة خيوط تُجري إيداعات وسحوبات في وقت واحد محمية بقفل خاص بكل حساب، يعود رصيد كل حساب في النهاية إلى قيمته الأولية.
def transaction(broker, balances, account, delta, log)
key = "account-#{account}"
ticket =
begin
broker.acquire(key, wait: WAIT, lease: LEASE)
rescue StandardError => e
log.error("account #{account} acquire failed: #{e}")
return
end
before = balances[account]
Thread.pass
after = before + delta
balances[account] = after
ticket.release
action, sign = delta < 0 ? ["withdraw", "-"] : ["deposit", "+"]
log.info("account #{account} #{action} #{sign}$#{AMOUNT} -> $#{after}")
endراجع الأمثلة الكاملة في test_example.rb, test_bank_example.rb, test_bench.rb.