Skip to content

Instantly share code, notes, and snippets.

@katpadi

katpadi/locky.rb Secret

Created June 28, 2016 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katpadi/6eae116f2a16b491800d4d3aa6167cfe to your computer and use it in GitHub Desktop.
Save katpadi/6eae116f2a16b491800d4d3aa6167cfe to your computer and use it in GitHub Desktop.
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