-
-
Save katpadi/6eae116f2a16b491800d4d3aa6167cfe to your computer and use it in GitHub Desktop.
locky
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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