[ZODB-Dev] Thread safety

Tim Peters tim at zope.com
Tue Oct 5 15:03:29 EDT 2004


[Dmitry Vasiliev]
>>> For example consider the following code:
>>>
>>> def getReply(request):
>>>     lock.acquire()
>>>     try:
>>>         try:
>>>             reply = _getReply(request)
>>>             transaction.commit()
>>>         except:
>>>             log.error("error", exc_info=True)
>>>             transaction.abort()
>>>             reply = None
>>>         return reply
>>>     finally:
>>>         lock.release()
>>>
>>> All persistent objects changes only inside _getReply() function. Two
>>> threads concurrently calls getReply() function...
>>>
>>> Is it safe? Is it possibly/safe to use only one connection object?

[Tim Peters]
>> *Offhand* I can't think of a reason for that breaking.  But it's not how
>> threads were intended to be used in ZODB, and I don't have spare time to
>> think about it.  Maybe someone else does.

[Dmitry Vasiliev]
> Thanks a lot!
>
> The only problem with the code above that it should use
> transaction.TransactionManager instead of default
> transaction.ThreadTransactionManager.

Unclear.  TransactionManager didn't exist before ZODB 3.3.  If you're
determined to muck with threads in this way in 3.3, I'd certainly recommend
creating an instance of TransactionManager, passing it to DB.open(), and
making all your explicit transaction operations through that same instance;
before 3.3, I'd recommend using the setLocalTransaction() method instead,
immediately after opening a Connection.

> Quote from ZODB.Connection.Connection docstring talk about this use case:

Not really.  It's unclear what it's talking about, exactly, but you want it
to cover your specific use case so you're inclined to read it that way
<wink>.

> """
>      Synchronization
>      ---------------
>
>      A Connection instance is not thread-safe.  It is designed to
>      support a thread model where each thread has its own transaction.
>      If an application has more than one thread that uses the
>      connection or the transaction the connection is registered with,
>      the application should provide locking.
> """

I'll translate:

    A Connection instance is not thread-safe.  It is designed to
    support a thread model where each thread has its own transaction,
    exactly like Zope does.  If you don't use threads in this way,
    it's hard to guess what will happen, but you're at least going
    to need locking of some sort or it will certainly fail horribly.
    If we knew exactly what needed to be protected by locks, and when,
    we would have explained that instead of giving vague "provide
    locking" advice.

IOW, you'll try something, and it will work or it won't.  If it doesn't
work, the resolution will be that you didn't "provide locking" at a correct
time in a correct way.  That's OK by me <wink>.



More information about the ZODB-Dev mailing list