<s> import random <EOL> from diesel import fork , quickstop , quickstart , sleep <EOL> from diesel . protocols . redis import RedisClient , RedisTransactionError , RedisLock , LockNotAcquired <EOL> """<STR_LIT>""" <EOL> key = '<STR_LIT>' <EOL> incr_key = '<STR_LIT>' <EOL> counter = <NUM_LIT:0> <EOL> """<STR_LIT>""" <EOL> lock_timeout = <NUM_LIT:3> <EOL> sleep_factor = <NUM_LIT:1> <EOL> def take_lock ( ) : <EOL> global counter <EOL> client = RedisClient ( '<STR_LIT:localhost>' , <NUM_LIT> ) <EOL> try : <EOL> with RedisLock ( client , key , timeout = lock_timeout ) as lock : <EOL> v = client . get ( incr_key ) <EOL> sleep ( random . random ( ) * sleep_factor ) <EOL> client . set ( incr_key , int ( v ) + <NUM_LIT:1> ) <EOL> counter += <NUM_LIT:1> <EOL> except LockNotAcquired : <EOL> pass <EOL> def main ( ) : <EOL> client = RedisClient ( '<STR_LIT:localhost>' , <NUM_LIT> ) <EOL> client . delete ( key ) <EOL> client . set ( incr_key , <NUM_LIT:0> ) <EOL> for _ in xrange ( <NUM_LIT> ) : <EOL> fork ( take_lock ) <EOL> if random . random ( ) > <NUM_LIT:0.1> : <EOL> sleep ( random . random ( ) / <NUM_LIT:10> ) <EOL> sleep ( <NUM_LIT:2> ) <EOL> assert counter == int ( client . get ( incr_key ) ) , '<STR_LIT>' <EOL> quickstop ( ) <EOL> quickstart ( main ) </s>
