2

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?

1 Answer 1

3

You are not using "thread locking", you are using process locking. Since processes don't share heap content, each time f gets different object.

See threading - Python library for operations with threads. It allows you to achieve needed behavior.

Probably just replace

from multiprocessing import Process, Lock
...
    Process(target=f, args=(a,lock)).start()

with

from threading import Thread, Lock
...
    Thread(target=f, args=(a,lock)).start()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works! In hindsight, the answer to my question was fairly simple, but there's a huge amount of complexity to those simple changes. I'll be spending some extra time looking at the differences between threading and multiprocessing. Thanks for the quick, accurate and helpful answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.