Method objects and locking

Robert Collins robertc at robertcollins.net
Sun Nov 27 22:45:18 GMT 2005


I noticed in a recent patch the following idiom with a MethodObject
pattern:


class MethodObject:
    def __init__(self, branch):
        self.branch = branch
        self.something = self.branch.get_something()

    def doTheThing(self):
        self.branch.lock_read()
        ...


This is buggy: There is a race condition between getting data from the
branch and then locking it. This is caused in two ways: there is no
guarantee of timeliness between constructing the object and using it;
there is an implicit lock() around all the branch accessor methods, but
it is released before the lock in doTheThing() is taken, so someone else
waiting on the lock in another process can take a lock out and
completely alter the branch first.

In general, with method objects:
 * All the work should occur in the named method - i.e. foo.commit() for
the commit method, foo.check() for the check method object.
 * The constructor *may* be given useful parameters to instantiate the
object, but nothing should be calculated or cached during __init__ - the
state of all the supplied objects may vary completely before the method
is invoked.

Cheers,
Rob

-- 
GPG key available at: <http://www.robertcollins.net/keys.txt>.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : https://lists.ubuntu.com/archives/bazaar/attachments/20051128/a0f5e8d6/attachment.pgp 


More information about the bazaar mailing list