[Zope-dev] Threads and locks

Michel Pelletier michel@digicool.com
Tue, 25 Apr 2000 07:14:49 -0700


Itamar Shtull-Trauring wrote:
> 
> I want to limit access to instances of a class I have - "Debt" - so that
> only one thread at a time will access a given instance.  Debt is used to
> keep tracking of how much people owe us, so I need to make sure they don't
> get charged twice, etc..
> 
> For example, the function:
> 
>         def dostuff(self):
>                 # only one thread at a time should call these two lines:
>                 sum = self.debtItem.get()
>                 self.debtItem.add(23 + sum)
> 
> Now, I could just use a global lock for all threads who call this function,
> but that would be a waste since I only don't want two threads accessing the
> same instance of Debt at the same time, not all instances.
> 
> In other words, if I have two instance of Debt called A and B, threads can
> access both A and B at the same time, but you can't have two thread
> accessing A at the same time.
> 
> I could add a lock to each instance of Debt.  However, each thread has it's
> own copy of all Persistent objects.  So each thread has its own copy of the
> lock.  If I do A.lock.acquire() in one thread, will another thread be
> acquiring the same lock if it does A.lock.acquire()?

No.  It will be a different lock, but it will be a different transaction
as well.  Any value for sum that the first line of code above gets will
not change in the second line, even if another thread changes its copy
of debtItem, those changes won't be reflected in the object in other
threads until its transaction is commited.

If another thread commits this same opeation before this thread does,
the usual conflit rules apply.  The commit will get a ConflictError, and
this request will start over and get a whole new copy of the objects
from the database complete with the newer values.  I'm not even sure if
locks are necessary at all, this code is threadsafe and as you pointed
out each thread gets its own copy of the object, the transacitonal
nature of change the objects should keep your data consistent at all
times.

-Michel