Skip to content

Instantly share code, notes, and snippets.

@silveira
Created December 17, 2013 16:06
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 silveira/8007377 to your computer and use it in GitHub Desktop.
Save silveira/8007377 to your computer and use it in GitHub Desktop.
why the objlock doesn't work? (i.e. it should count to 10000)
import time
import threading
class objnolock(object):
def __init__(self,c):
self.c=c
def inc(self):
new = self.c+1
time.sleep(0.001)
self.c = new
class objlock(object):
def __init__(self,c):
self.c=c
self.lock = threading.Lock()
def inc(self):
with self.lock:
new = self.c+1
time.sleep(0.001)
self.c = new
nolock = objnolock(0)
lock = objlock(0)
for _ in range(10000):
threading.Thread(target=nolock.inc).start()
threading.Thread(target=lock.inc).start()
print "with lock", nolock.c # wrong result. about 20% of the answer.
print "no lock", lock.c # also wrong results.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment