Is += on strings a thread-safe operation?

Tim Peters tim.one at home.com
Wed Feb 28 15:49:42 EST 2001


[Warren Postma, correctly explains Python's peculiarly forgiving notion
 of thread-safety as follows from the global interpreter lock, but
 falls for a flawed example]

> ...
> 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 "+=".

There's the rub:  += generates more than one bytecode, so there actually are
chances for the interpreter to let go of the GIL "in the middle" of *any* +=
(and for multiple spellings of "+=").

> In other words, anything that resolves to a single bytecode in Python
> interpreter is done while the current thread holds the lock.

Yes.

> That makes invocation of any builtin C function atomic as far as
> I can see.

Your eyes are fine -- at least for long-term viewing <wink>.

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

I only show up when I'm not really needed -- like here.

it's-too-stressful-to-take-a-stand-when-i-am-needed-ly y'rs  - tim





More information about the Python-list mailing list