Is += on strings a thread-safe operation?

Warren Postma embed at geocities.com
Wed Feb 28 15:25:05 EST 2001


"Stefan Franke" <spamfranke at bigfoot.de> wrote in message
news:3a9d3833.737414 at news.btx.dtag.de...
> What about augmented assignments of other built-in types?  Being able to
thread-safely append
> to a string buffer  (or other sequences) with += would be a big advantage
of the somewhat infamous
> augmented assignment operators in my eyes.
>
> Stefan

The sad truth is that everything in Python is thread safe, because
ironically, nothing in python is thread safe.

What I mean to say is that when Threading support is enabled in Python,
which on most systems it now is, everything the Python interpreter runs
occurs while it is holding onto a Global Interpreter Lock which is only
released explicitly when it is safe to do so.

So that means in effect that all Python Bytecode operations are explicitly
atomic, thus all Python builtin C functions are atomic, except those which
choose not to be (such as time.sleep()) by letting go of and then
re-acquiring the global interpreter lock.  It is not possible for the
interpreter to let go of that lock while in the middle of a string "+=".

In other words, anything that resolves to a single bytecode in Python
interpreter is done while the current thread holds the lock. That makes
invocation of any builtin C function atomic as far as I can see.

Am I right? Where is Timbot when you really need him?  <grin>

Warren





More information about the Python-list mailing list