Skip to content

Instantly share code, notes, and snippets.

@tonylampada
Created May 23, 2014 10:28
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 tonylampada/b7762bcbb8919caf632a to your computer and use it in GitHub Desktop.
Save tonylampada/b7762bcbb8919caf632a to your computer and use it in GitHub Desktop.
How to solve racing conditions in python using shared memory
import time
from threading import Thread
import random
d1 = {}
def run(n):
for i in range(3):
c = d1['c']
print('Thread %s read c=%s' % (n, c))
time.sleep(1)
c += 1
d1['c'] = c
print('Thread %s wrote c=%s' % (n, c))
time.sleep(random.random())
def racing():
d1['c'] = 0
t1 = Thread(target=run, args=(1,))
t2 = Thread(target=run, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
c = d1['c']
print('Finish. c = %s' % c)
memcache = {}
def waitforlock(name, timeout=0):
start = time.time()
locked = memcache.get(name)
def should_wait_for_timeout():
return timeout <= 0 or time.time() - start < timeout
while(locked and should_wait_for_timeout()):
time.sleep(0.1)
locked = memcache.get(name)
if not locked:
memcache[name] = True
return not locked
def releaselock(name):
del memcache[name]
class lockon():
def __init__(self, name):
self.name = name
def __enter__(self):
gotlock = waitforlock(self.name)
if not gotlock:
raise BaseException('cannot get lock for %s' % self.name)
def __exit__(self, type, value, traceback):
releaselock(self.name)
def controlled_run(n):
for i in range(3):
with lockon('write_to_c'):
c = d1['c']
print('Thread %s read c=%s' % (n, c))
time.sleep(1)
c += 1
d1['c'] = c
print('Thread %s wrote c=%s' % (n, c))
time.sleep(random.random())
def racing_solved():
d1['c'] = 0
t1 = Thread(target=controlled_run, args=(1,))
t2 = Thread(target=controlled_run, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
c = d1['c']
print('Finish. c = %s' % c)
racing(); # hum, this is not good
racing_solved(); # now, this works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment