Make a small function thread safe

Tim Delaney timothy.c.delaney at gmail.com
Fri Dec 16 15:47:09 EST 2011


On 17 December 2011 02:05, Brad Tilley <kj4eit at gmail.com> wrote:

> On Dec 16, 9:36 am, Tim Wintle <tim.win... at teamrubber.com> wrote:
>
> > should be:
> >       def run(t):
> >           with lock:
> >               shared_container.append(t.name)
> >
> > (or lock.acquire() and lock.release() as you mentioned)
>
>
> Thanks Tim. The with statement is closer to the C++ code (IMO) more so
> than the explicit acquire() and release() so I'll use that approach. I
> appreciate your advice.


Most definitely. The acquire/release code shown was erroneous, since it
would not release if an exception was thrown. The with code is effectively
equivalent to:

    lock.acquire()

    try:
        ...
    finally:
        lock.release()

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111217/24196e6e/attachment-0001.html>


More information about the Python-list mailing list