I've encountered an unexpected behavior with threading. I've attached a short example below to demonstrate the behavior:
from multiprocessing import Process, Lock
import time
class inc:
def __init__(self):
print "Initializing a new class"
self.value = 0
def add_one(self):
self.value += 1
print self.value
def f(a,l):
# Do something using a class call
l.acquire()
a.add_one()
l.release()
#Do something that takes a long time
time.sleep(5)
#Do a different thing using a class call
l.acquire()
a.add_one()
l.release()
if __name__=="__main__":
a=inc()
lock = Lock()
for i in range(0,4):
Process(target=f, args=(a,lock)).start()
The output I'm looking for is 1,2,3,4,5,6,7,8 but I get: 1,1,1,1,2,2,2,2. Am I using thread locking properly? Only one instance of the class exists and I serialize thread access to the class, so why doesn't the class variable increment?