ask the boss to solve the problem, thank you.
-sharp 6-8
-sharp <start id="_1314_14473_8641"/>
def acquire_lock(conn, lockname, acquire_timeout=10):
-sharp 128
identifier = str(uuid.uuid4())
end = time.time() + acquire_timeout
while time.time() < end:
-sharp
if conn.setnx("lock:" + lockname, identifier):
return identifier
time.sleep(.001)
return False
-sharp <end id="_1314_14473_8641"/>
-sharp 6-9
-sharp <start id="_1314_14473_8645"/>
def purchase_item_with_lock(conn, buyerid, itemid, sellerid):
buyer = "users:%s" % buyerid
seller = "users:%s" % sellerid
item = "%s.%s" % (itemid, sellerid)
inventory = "inventory:%s" % buyerid
-sharp
locked = acquire_lock(conn, "market:")
if not locked:
return False
pipe = conn.pipeline(True)
try:
-sharp
pipe.zscore("market:", item)
pipe.hget(buyer, "funds")
price, funds = pipe.execute()
if price is None or price > funds:
return None
-sharp
pipe.hincrby(seller, "funds", int(price))
pipe.hincrby(buyer, "funds", int(-price))
pipe.sadd(inventory, itemid)
pipe.zrem("market:", item)
pipe.execute()
return True
finally:
-sharp
release_lock(conn, "market:", locked)
-sharp <end id="_1314_14473_8645"/>
-sharp 6-10
-sharp <start id="_1314_14473_8650"/>
def release_lock(conn, lockname, identifier):
pipe = conn.pipeline(True)
lockname = "lock:" + lockname
while True:
try:
-sharp
pipe.watch(lockname)
if pipe.get(lockname) == identifier:
-sharp
pipe.multi()
pipe.delete(lockname)
pipe.execute()
return True
pipe.unwatch()
break
-sharp ;
except redis.exceptions.WatchError:
pass
-sharp
return False
-sharp <end id="_1314_14473_8650"/>