Created
December 17, 2013 16:06
-
-
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)
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
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