Make a small function thread safe

John Nagle nagle at animats.com
Fri Dec 16 21:18:32 EST 2011


On 12/16/2011 2:08 PM, Lie Ryan wrote:
> On 12/17/2011 01:30 AM, Brad Tilley wrote:
>> Or perhaps run should look like this instead:
>>
>> def run(t):
>> lock.acquire()
>> shared_container.append(t.name <http://t.name>)
>> lock.release()
>>
>> That seems a bit barbaric to me, not sure.
>
> change that to:
>
> def run(t):
> with lock:
> shared_container.append(t.name <http://t.name>)
>
>
> the `with-statement` will call lock.acquire() and lock.release().
>

    And, importantly, if you leave the "with" via an exception, the
lock will be unlocked.

					John Nagle




More information about the Python-list mailing list