Are python objects thread-safe?

Aaron Brady castironpi at gmail.com
Sun Dec 21 18:17:12 EST 2008


On Dec 21, 12:51 pm, RajNewbie <raj.indian... at gmail.com> wrote:
> Say, I have two threads, updating the same dictionary object - but for
> different parameters:
> Please find an example below:
> a = {file1Data : '',
>        file2Data : ''}
>
> Now, I send it to two different threads, both of which are looping
> infinitely:
> In thread1:
> a['file1Data'] = open(filename1).read
>           and
> in thread2:
> a['file2Data'] = open(filename2).read
>
> My question is  - is this object threadsafe? - since we are working on
> two different parameters in the object. Or should I have to block the
> whole object?

Threads take turns with the Global Interpreter Lock, so a Python
thread is sure to have the GIL before it calls a method on some
object.  So yes, with the rare exception (that I don't want to not
mention) that if you've got non-Python threads running in your process
somehow, they don't make the guarantee of enforcing that.



More information about the Python-list mailing list