Jason S
Jason S

Reputation: 189686

Correct usage of Python threading.RLock

I haven't used the threading library much in Python, so my confidence is a little shaky compared to concurrency in other languages... is this a correct way to use a threading.RLock() object as a mutex?

class MyObj(object):
    def __init__(self):
        self.mutex = threading.RLock()

    ...

    def setStatistics(self, statistics):
        with self.mutex:
            self._statistics = statistics
    def getStatistics(self):
        with self.mutex:
            return self._statistics.copy()

In particular I want to make sure that the self._statistics.copy() step happens while the mutex is still acquired.

Is there any other gotcha I need to be aware of? The self._statistics object is a large numpy array and I need to make sure it is transferred properly and in a consistent state between threads.

Upvotes: 0

Views: 71

Answers (1)

dano
dano

Reputation: 94891

Yep, that's the right way to use it. When you use this statement:

with self.mutex:
    return self._statistics.copy()

The lock won't be released until after the self._statistics.copy() operation completes, so its safe. Here's a demo:

import threading

class MyLock(threading._RLock):
    def release(self):
        print("releasing")
        super(MyLock, self).release()

class Obj():
    def test(self):
        print "in test"

l = MyLock()
obj = Obj()

def f():
    with l:
        return obj.test()

f()

Output:

in test
releasing

Upvotes: 1

Related Questions