Create a gist now

Instantly share code, notes, and snippets.

@katpadi /locky.rb Secret
Created Jun 28, 2016

What would you like to do?
locky
coups = Coupon.all.sample
coups.lock! # no other users can read this coupon, they have to wait until the lock is released
coups.save! # lock is released, other users can now read this
# Get a coupon
@coupon = Coupon.all.sample
@coupon.with_lock do
@coupon.balance += 5
@coupon.save!
end
# Try this
@coupon = Coupon.first
# Make the two processes, access the same instance
sleep 10
@coupon.with_lock do
@coupon.balance += 5
@coupon.save!
end
module Locky
module_function
def unsafe(coupon, val = 1)
sleep 8
puts coupon.balance
sleep 2
coupon.balance += val
coupon.save!
puts "Final: #{coupon.balance}"
end
def safe(coupon, val = 1)
sleep 8
coupon.with_lock do
puts coupon.balance
sleep 2
coupon.balance += val
coupon.save!
puts "Final: #{coupon.balance}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment